我被困在如何正確使用URLSession
任務下載J.S.Bach圖像到UIImage
。 這是viewDidLoad
的代碼。沒有崩潰發生。程序永遠不會到達最內層的if語句,並且UIImageView
保持空白。無法使用URLSession下載圖像
let url = URL(string: "https://it.wikipedia.org/wiki/File:Johann_Sebastian_Bach.jpg")
let request = URLRequest(url: url!)
let task = URLSession.shared.dataTask(with: request, completionHandler: {(data, response, error) -> Void in
if error != nil {
print("some error!")
} else {
if let bach = UIImage(data: data!) {
self.image.image = bach
}
}
})
task.resume()
檢查響應。 –
嘗試使用此網址,因爲您正在使用的網址會返回網頁。 https://upload.wikimedia.org/wikipedia/commons/6/6a/Johann_Sebastian_Bach.jpg – Michael