Topics

#78: NSURLSession Basics 🔗

Topics

NSURLSession is the heart of networking in Foundation. Let's take a look at a few ways to use it.

The basic idea is we'll create a new NSURLSession, and then use it to create NSURLSessionTasks that will make the actual HTTP requests. We'll start by creating a new session:

let session = NSURLSession(
  configuration: NSURLSessionConfiguration.defaultSessionConfiguration(),
  delegate: self,
  delegateQueue: nil
)

Now we'll use the session to create different tasks to do our bidding:

Call HTTP API

let url = NSURL(string: "http://api.apple.com/releaseSchedule")!
let task = session.dataTaskWithURL(url)
task.resume()

Download Data

We'll can use a data task like above, then use this function to grab the downloaded data. This will be called multiple times, so we'll need to keep an NSMutableData reference around to append to.

func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData)

Upload Data

Here we're uploading an NSData. There's also another form of uploadTaskWithRequest that accepts a file URL to upload from.

let request = NSMutableURLRequest(
  URL: NSURL(string: "http://api.someservice.com/upload")!
)

request.HTTPMethod = "POST"

let task = session.uploadTaskWithRequest(request, 
  fromData: dataToUpload)

task.resume()