Open Search

Returning a return value from a resume() callback in Swift

January 19, 2016 9:50 am
Categorised in:
Reading Time: 1

Having trouble with Swift functions that run an async session e.g. getting image or JSON data from a server? Me too. This post on Stack Overflow saved my mental state from debilitating further.

To fix you want to set your function up like this:

 getJsonOffServer(imageId: String, completion: ((image: UIImage?) -> Void)) {
    let url:String = "https://dummyUrl.com/\(imageId).jpg"

    let task = NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: url)!) {(data, response, error) in
//Do stuff... and when finished use the completion
        completion(image: UIImage(data: data))
    }

    task.resume()
}

and call it like this:

getImageFromServerById("some string") { image in
    dispatch_async(dispatch_get_main_queue()) {
        // go to something on the main thread with the image like setting to UIImageView
    }
}

Dear Stack Overflow user 0x7fffffff, thank you for answering that, it was doing my actual head in and wasting far too much of my time.

This joint was penned by @elmarko