Making HTTP Requests in Swift
The same options for making HTTP GET requests that are available in Objective-C can be used with Swift. I’ll only cover those that don’t involve using third party libraries such as AFNetworking.
Using NSURLSession
First, initialize an NSURL object and an NSURLSessionDataTask from NSURLSession. Then, run the task with resume().
let url = NSURL(string: “http://www.stackoverflow.com")let task = NSURLSession.sharedSession().dataTaskWithURL(url) {(data, response, error) in
println(NSString(data: data, encoding: NSUTF8StringEncoding))
}task.resume()
Pretty straightforward. Also, the block syntax in Swift is much more pleasant to read and write, specially when benefiting from trailing blocks, which is possible since the block parameter is the last argument to the NSURLSessionDataTask initializer.
Using NSURLConnection
First, initialize an NSURL and an NSURLRequest:
let url = NSURL(string: “http://www.stackoverflow.com")
let request = NSURLRequest(URL: url)
Then, you can load the request asynchronously with:
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
println(NSString(data: data, encoding: NSUTF8StringEncoding))
}
Or you can initialize an NSURLConnection:
let connection = NSURLConnection(request: request, delegate:someObject, startImmediately: true)
Just make sure someObject implements the NSURLConnectionDataDelegateprotocol, and then deal with the data received in the appropriate delegate methods.
For more detail, check the documentation for the NSURLConnectionDataDelegateprotocol
Testing on an Xcode playground
In order to try this on an Xcode playground, add import XCPlayground to your playground, as well as the following call:
XCPSetExecutionShouldContinueIndefinitely()
This will allow you to use asynchronous code in playgrounds.
Final remarks
While I provided code that uses both NSURLSession and NSURLConnection,NSURLSession is the preferred solution. Even though NSURLConnection isn’t officially deprecated, this has been stated by Apple engineers on several occasions during WWDC sessions.
Finally, here’s a gist with the NSURLSession based implementation.
Adapted from my answer on Stack Overflow
This article was originally posted at My Own Thing, my own personal blog where I write and share about the things I make and stuff I care for.