当我的应用程序想要下载头像(个人资料图片)时,它会崩溃并显示错误但我的图像不是nil但是应用程序检测到它的nil是错误按摩
致命错误:在解包可选值时意外发现nil
这里是我的图像的打印数据和图像,证明图像不是零
,{0,0} 10059字节
这是我下载阿凡达的代码(个人资料图片)
let avatarUrl = URL(string: "http://example.com/uploads/avatar/\(EmailSignInViewController.avatar)")!
let session = URLSession(configuration: .default)
// Define a download task. The download task will download the contents of the URL as a Data object and then you can do what you wish with that data.
let downloadPicTask = session.dataTask(with: avatarUrl) { (data, response, error) in
// The download has finished.
if let e = error {
print("Error downloading cat picture: \(e)")
} else {
// No errors found.
// It would be weird if we didn't have a response, so check for that too.
if let res = response as? HTTPURLResponse {
print("Downloaded personal picture with response code \(res.statusCode)")
if let imageData = data {
// Finally convert that Data into an image and do what you wish with it.
print(imageData)
print(profileViewController.userImage)
if #available(iOS 10, *) {
profileViewController.userImage = UIImage(data: imageData )!
} else {
profileViewController.userImage = UIImage(named: "user.jpg")!
}
// Do something with your image.
} else {
print("Couldn't get image: Image is nil")
}
}
else {
print("Couldn't get response code for some reason")
}
}
}
downloadPicTask.resume()