Mobile Tech Talk

Tech Talk: why it’s time to switch to NSURLSession

We are happy to share articles pertaining to programming, coding and related topics in our new series: Tech Talk. This week’s article is about NSURLSession vs NSURLConnection, written by Dhanaraj, Software Architect.

Us software architects have been using NSURLConnection for network connections and it has served most of our requirements for years now. However, it required us to write lot of code to accommodate performance and data transfers.

Apple has released NSURLSession APIs for iOS 7.0 onwards and it has made life a lot easier for us:

NSURLConnection Code

let queue: NSOperationQueue = …
let url = NSURL(string: “https://www.example.com”)!
let request = NSURLRequest(URL: url)
NSURLConnection.sendAsynchronousRequest(request, queue: queue) {
(response: NSURLResponse?, data: NSData?, error: NSError?) in
}

NSURLSession Code

let url = NSURL(string: “https://www.example.com”)!
let request = NSURLRequest(URL: url)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
(data: NSData?, response: NSURLResponse?, error: NSError?) in

}
task.resume()

Following are the main advantages of NSURLSession over NSURLConnection

– Fetching of data via network is easy
– Upload and download of data in the background
– Rich delegate methods
– Get the progress of loading, download, upload.
– Option to Cancel, Pause, Resume, Restart the download/upload network operations.
– Multiple session configurations to suit the application requirement
– Can provide different settings for different sessions.
– Private sessions, Cookies, Storage
– Support for HTTP1.1 and HTTP 2.0 automatically. No source code changes required.
– Uses best available connectivity (iPhone or WiFi)
– Switching to NSURLSession is easy
– Watch OS 2 only supports NSURLSession, It encourages reusability code in between iOS and Watch OS apps.
– Performance is better and well supported by Apple

Following are the main disadvantages of NSURLConnection

– Watch OS2 does not support NSURLConnection
– Lot of coding is required
– Get the progress of loading, download, upload.

Any comments on your experience? Do share with us.

Dhanaraj - Software Architect
Dhanaraj is a Solutions Architect and has a thorough knowledge of the app or product life-cycle from conceptualization to delivery.
consultation-here

Want to learn how Robosoft can
take your mobile strategy to the next level?

You may also like
Dependency manager to ease the use of libraries
The destiny of push‑notifications

Leave Your Comment

Your Comment*

Your Name*
Your Webpage