UIImage swift3 update

I have default images in the viewController, and after user action, it loads the external image and replaces it with the default.

The problem is, it downloads the image, but it does not update unless I change the viewController to another

  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 printout img refreshed, but nothing changes in the interface, what am I missing?

+4
source share
2 answers

Can you set the image in 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")
        }
    })
}
+3
source

you do not need to put it in the GCD queue.

( ). , , .

self.getDataFromUrl(imageURL, completion: { [unowned self] (data) in
                let image = UIImage(data: data!)
                self.imageView.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()
    }

, .

0

Source: https://habr.com/ru/post/1656355/


All Articles