Make an HTTP request asynchronously

 Problem

I want to make an asynchronous HTTP request, given a target URL.



 Recipe


// Set the URL where we're making the request
let request = NSURLRequest(URL: NSURL(string: "http://iswift.org")!)

// Perform the request
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{
        (response: NSURLResponse?, data: NSData?, error: NSError?)-> Void in

            // Get data as string
            let str = NSString(data: data!, encoding: NSUTF8StringEncoding)
            print(str)
        }
    );
				

Heard the news?

The Swift Cookbook for Swift 3 is at last here! For iBooks, Kindle and Paperback.
Hurry up - and Check it out! ;-)

 

 Playground