Christian Sousa
06/16/2020, 4:19 PMprivate fun getDataFromUrl(url: NSURL) {
NSURLSession.sharedSession.dataTaskWithURL(
url = url,
completionHandler = ::getCompletion.freeze()
).resume()
}
So with this, I will get data from a URL
After that, with my getCompletion
fun getCompletion(data: NSData?, response: NSURLResponse?, error: NSError?){
var downloadedImage = UIImage(data = data)
logo.setImage(image = downloadedImage)
logo.setHidden(false)
}
Where my logo is a UIImage.
Problem is, the getCompletion
is being called from a background thread and I’m trying to update something on the main thread.
Is there any way of doing this?
The goal is to be able to download the image asynchronously and after that, update the image I already have.
What I’m getting as an error is the following:
Main Thread Checker: UI API called on a background thread: -[UIImageView setImage:]
Sam
06/17/2020, 4:38 PMChristian Sousa
06/17/2020, 4:39 PMSam
06/17/2020, 4:43 PMdispatch_async(dispatch_get_main_queue()) {
//do work on the main thread
}
That’s the basic form. In practice you’ll probably have to freeze the block before sending it to the dispatch_async
function.