Using closures for asynchronous coding

suggest change

Closures are often used for asynchronous tasks, for example when fetching data from a website.

func getData(urlString: String, callback: (result: NSData?) -> Void) {

    // Turn the URL string into an NSURLRequest.
    guard let url = NSURL(string: urlString) else { return }
    let request = NSURLRequest(URL: url)
    
    // Asynchronously fetch data from the given URL.
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {(data: NSData?, response: NSURLResponse?, error: NSError?) in

        // We now have the NSData response from the website.
        // We can get it "out" of the function by using the callback 
        // that was passed to this function as a parameter.

        callback(result: data)
    }
        
    task.resume()
}

This function is asynchronous, so will not block the thread it is being called on (it won’t freeze the interface if called on the main thread of your GUI application).

print("1. Going to call getData")

getData("http://www.example.com") {(result: NSData?) -> Void in

    // Called when the data from http://www.example.com has been fetched.
    print("2. Fetched data")
}

print("3. Called getData")

Because the task is asynchronous, the output will usually look like this:

"1. Going to call getData"
"3. Called getData"
"2. Fetched data"

Because the code inside of the closure, print("2. Fetched data"), will not be called until the data from the URL is fetched.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents