Özgür Ersil Özgür Ersil - 2 months ago 31
Swift Question

UIImage refresh swift3

I have some default images in the viewController and after a user action, it loads an external image and replace the default one.

The problem, it loads the image but doesnt refresh unless i change the viewController to other one

DispatchQueue.main.async {
self.getDataFromUrl(thumbURL, completion: { (data) in
let image = UIImage(data: data!)
self.cityImageView.image = image
print("img refreshed")
})
}

func getDataFromUrl(_ url:String, completion: @escaping ((_ data: Data?) -> Void)) {
URLSession.shared.dataTask(with: URL(string: url)!, completionHandler: { (data, response, error) in
if let newData = data {
completion(newData)
}
}) .resume()
}


So i get a print out
img refreshed
but in front-end nothing changes, what am i missing?

Answer

Can you set image on the main thread?

DispatchQueue.main.async {
    self.getDataFromUrl(thumbURL, completion: { (data) in
        DispatchQueue.main.async {
            let image = UIImage(data: data!)
            self.cityImageView.image = image
            print("img refreshed")
        }
    })
}