What is NSURLSession? How is it used?
Ans: NSURLConnection became obsolete and the new Apple standard for implementing HTTP networking is NSURLSession. NSURLSession and related classes do a lot of heavy lifting for basic HTTP connection and authentication for you. It allows you to send HTTP verb (GET, POST, etc.) requests, connect to FTP, and to download files. You can option- ally configure cache and execute your requests in a background/app suspended state. Overall the structure of NSURLSession-related things looks like the following:
The way you typically work with it is to use NSURLSessionDownloadTask objects to execute requests against given urls. It has a block-based and delegate-based API, which means there are two ways you can issue HTTP requests with
NSURLSession: either by receiving a completion handler block callback or by implementing delegate methods and receiving notifications as the data comes in. Either way is fine and has a different purpose depending on your use case (for example, if you’d like to receive download progress notification you would want to implement delegate callbacks rather than a completion block). Also NSURLSession allows you to resume, cancel, or pause networking task.
All and all, NSURLSession is a very robust way of doing HTTP and other net- working but in reality, it is a bit too low level, and in the majority of the cases, you’re better off using a wrapper library like AFNetworking or Alamofire. Both of them are the de facto standard for networking on iOS, and use NSURL- Session under the hood to run HTTP requests for you.