我使用unsplash.it将一些图像下载到imageView。 当我点击屏幕图像从unsplash下载并刷新imageview。 当我从表视图控制器函数调用函数downloadImage()时,由于致命错误,在self.screenImg.image = image时崩溃:在展开Optional值时意外发现nil。为什么会这样?
我想我应该将screenImg设置为nil,然后在screenImg中从unsplash设置新图像,但即使在此之后应用程序仍然崩溃。 我怎么解决呢? image reference here
MainViewController
@IBOutlet weak var screenImg: UIImageView!
@IBAction func changeImgBtn(_ sender: AnyObject) {
print("screen pressed")
downloadImage()
}
func downloadImage() {
let pictureURL = URL(string: "https://unsplash.it/g/750/1334/?random")!
let session = URLSession(configuration: .default)
let downloadPicTask = session.dataTask(with: pictureURL) { (data, response, error) in
// The download has finished.
if let e = error {
print("Error downloading picture: \(e)")
} else {
if let res = response as? HTTPURLResponse {
print("Downloaded cat picture with response code \(res.statusCode)")
if let imageData = data {
let image = UIImage(data: imageData)
DispatchQueue.main.async() {
self.screenImg.image = image
}
} else {
print("Couldn't get image: Image is nil")
}
} else {
print("Couldn't get response code for some reason")
}
}
}
downloadPicTask.resume()
}
TableViewController
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 1 {
if mainViewController.screenImg?.image == nil {
print("it is nil")
} else {
print("it is not nil")
}
mainViewController.screenImg?.image = nil
mainViewController.downloadImage()
print("screen is pressed from menu")
navigationController?.popViewController(animated: true)
dismiss(animated: true, completion: nil)
}