I am using unsplash.it to download some images to an imageView. When i click the screen image is downloaded from unsplash and refresh imageview. When I call function downloadImage() from table view controller application crashes at self.screenImg.image = image because of fatal error: unexpectedly found nil while unwrapping an Optional value. why is this happening?
I guess i should set screenImg to nil, and then set the new image from unsplash in screenImg, but even after this the application keeps crashing. how can i solve it? 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)
}