NSURLSession & NSURLConnection with Swift

NSURLSession

An example of using NSURLSession in Swift. Note, to do this in an Xcode Playground, you’ll need to import XCPlayground and call XCPSetExecutionShouldContinueIndefinitely()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import Cocoa
import XCPlayground

// allow the asynchronous task to continue, set timeout in console
XCPSetExecutionShouldContinueIndefinitely()

let url = NSURL(string:"http://97.88.225.91:5309/scheck")
var session = NSURLSession.sharedSession()

// use a separate handler function in lieu of doing it inline for clarity
func apiHandler(data:NSData!, response:NSURLResponse!, error:NSError!) {
if error {
println("API error: \(error), \(error.userInfo)")
}
var jsonError:NSError?
var json:NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &jsonError) as NSDictionary
if jsonError {
println("Error parsing json: \(jsonError)")
}
else {
let status:String? = json["msg"] as? String
println("server status: \(status)")
}
}
var task:NSURLSessionDataTask = session.dataTaskWithURL(url, completionHandler:apiHandler)
task.resume()

NSURLConnection

If we wanted to do the same thing with NSURLConnection:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import Cocoa
import XCPlayground

// allow the asynchronous task to continue, set timeout in console
XCPSetExecutionShouldContinueIndefinitely()

let url = NSURL(string:"http://97.88.225.91:5309/scheck")
let urlReq = NSURLRequest(URL: url)
let queue = NSOperationQueue()

NSURLConnection.sendAsynchronousRequest(urlReq, queue: queue, completionHandler: { (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
if error {
println("API error: \(error), \(error.userInfo)")
}
var jsonError:NSError?
var json:NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &jsonError) as NSDictionary
if jsonError {
println("Error parsing json: \(jsonError)")
}
else {
let status:String? = json["msg"] as? String
println("server status: \(status)")
}
})

References