Advantages of NSURLSession over NSURLConnection in iOS and Sample Demo Code

By | March 30, 2016

In an application we usually works with

  1. Data tasks – Data tasks are used for requesting data from a server, such as JSON data. These data are usually stored in memory and never touches the File System We can use NSURLSessionDataTask.
  2. Upload Tasks – Upload tasks are used to upload data to a remote destination. We can use NSURLSessionUploadTask.
  3. Download Tasks – Downloading a file and Storing in a temporary location. We can use NSURLSessionDownloadTask.

Difference between NSUrlConnection and NSUrlSession

  • NSURLSession is designed around the assumption that you’ll have a lot of requests that need similar configuration (standard sets of headers, etc.), and makes life much easier.
  • NSURLSession also provides support for background downloads, which make it possible to continue downloading resources while your app isn’t running (or when it is in the background on iOS).
  • NSURLSession also provides grouping of related requests, making it easy to cancel all of the requests associated with a particular work unit.
  • NSURLSession also provides nicer interfaces for requesting data using blocks, in that it allows you to combine them with delegate methods for doing custom authentication handling, redirect handling, etc., whereas with NSURLConnection, if you suddenly realized you needed to do those things, you had to refactor your code to not use block-based callbacks.


Sample Demo

While working with NSURLSession, you need to create an instance of NSUrlSession class. It handles the requests and responses, configures the requests, manages session storage and state, etc. The session object we just created uses the global NSURLCache, NSHTTPCookieStorage, and NSURLCredentialStorage.

NSURLSession iOS

To Create an session data task

let _url = NSURL(string: demo_url)

let dataTask : NSURLSessionDataTask = session.dataTaskWithURL(_url!, completionHandler: {(data, reponse, error) in
	if(error != nil){
			let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! NSDictionary
		} catch {
			// handle error



To create a NSURLSessionDownloadTask

To Create a NSURLSessionDownloadTask to download an image with Delegate functions from NSURLSessionDelegate,NSURLSessionDataDelegate,NSURLSessionDownloadDelegate. Add these classes to your ViewController

func downloadTask() {

	self.imageView.image = nil;
	self.pb.hidden = false
	self.pb.progress = 0

	let _url = NSURL(string: image_download_url)

	let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
	let manqueue = NSOperationQueue.mainQueue()
	session = NSURLSession(configuration: configuration, delegate:self, delegateQueue: manqueue)
	dataTask = session.dataTaskWithRequest(NSURLRequest(URL: _url!))



func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) {
	print("Description \(response.description)")

func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64)
	let progress : Double = Double(totalBytesWritten) / Double(totalBytesExpectedToWrite)
	dispatch_async(dispatch_get_main_queue()) {
		self.pb.progress = Float(progress)

func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64){

func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask) {

func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
	print("Local save Location : \(location)");
	print("Download Description \(downloadTask.response!.description)")
		let data : NSData = try NSData(contentsOfURL: location, options: NSDataReadingOptions())
		dispatch_async(dispatch_get_main_queue()) {
			self.imageView.image = UIImage(data : data);
			self.pb.hidden = true
			self.imageView.hidden = false

NSURLSessionUploadTask to create an Upload Task (POST)

let url:NSURL = NSURL(string: sampleUploadUrl)!
let session = NSURLSession.sharedSession()

let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData

let data = sampleData.dataUsingEncoding(NSUTF8StringEncoding)

let task = session.uploadTaskWithRequest(request, fromData: data, completionHandler:
	{(data,response,error) in
		guard let _:NSData = data, let _:NSURLResponse = response  where error == nil else {
		let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding)


You can download the complete iOS Source Code from here.

One thought on “Advantages of NSURLSession over NSURLConnection in iOS and Sample Demo Code

  1. Pingback: Interview Questions For iOS – mayankgupta516

Leave a Reply

Your email address will not be published. Required fields are marked *