Hello! I’m trying to do something but I’m unable t...
# kotlin-native
c
Hello! I’m trying to do something but I’m unable to right now, what I have is the following:
Copy code
private 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
Copy code
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:
Copy code
Main Thread Checker: UI API called on a background thread: -[UIImageView setImage:]
s
This is normally done by using GCD to dispatch back onto the main thread. You can create your UIImage and then dispatch over to the main thread and set the UIImageView.image to your downloaded image.
c
Is there any example of that so I can take a look into it?
s
Copy code
dispatch_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.