When trying to generate a random image from the web, I'm getting a fatal error because nil was found when returning the self.imageVar in the generateImage() function after resuming the data task.
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var imageVar: UIImage?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
tableView.dataSource = self
tableView.delegate = self
generateImage()
}
func generateImage() -> UIImage {
let url = URL(string: "https://picsum.photos/200/300")
let task = URLSession.shared.dataTask(with: url!) {
(data, response, error) in
if let data = data {
DispatchQueue.main.async() {
self.imageVar = UIImage(data: data)
}
} else {
print("Error")
}
}
task.resume()
return self.imageVar!
}
@IBAction func reloadImage(_ sender: Any) {
generateImage()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!
cell.imageView?.image = imageVar
return cell
}
}
How can I fix this?