HandsOn: NSURLSession Tutorial
By José Silva
We are designing Bolina to make all HTTP Libs faster and easily integrate with each one of them so, at some point, I had the task of exploring the iOS HTTP libraries landscape. After having an overview of the most popular ones, I went on to experience how to use an iOS native networking library. In the meantime, I put it all on paper to give a hand to anyone looking to have a feeling of what that means. That’s why I created this demo project.
In this hands-on NSURLSession tutorial, the native iOS modern API for networking, we will see how we can use it to fetch some data from a public API printing the results to the XCode console.
The project
The project itself is a simple exercise, in which I need to fetch some data from Cocoapods metrics API. The API provides metrics regarding the usage of libraries available through Cocoa Framework, which allows us to take a broader picture of the library’s usage. If you’re interested to see the complete code, you can clone it here and take a closer look.
In mobile development, a pretty common task is to download or upload data from web services. I didn’t need to upload data for this specific project, but I’ll show you an example so you can test it to a public API, such as https://httpbin.org/#/.
Downloading data
Downloading data from a web service with NSURLSession can be as simple as this:
- Define the NSURLSession that you will use. You can create one or use one of the available like the shared session;
- Specify the resource URL you want to download;
- Create the NSURLSessionDataTask that will download the data, calling, in the end, the completionHandler with the response, data or possible error;
- Completion handler definition: you have the chance to inspect the data returned and take action over it. For instance, in our example we will parse the json response, but here is where we handle services such as caching;
- NSURLSession tasks don’t start on their declaration, for that you need to call the resume;
Uploading data
If you checked out the repo you will find this method definition:
- Define the NSURLSession that you will use. You can create one or use one of the available, like the shared session;
- Specify the request to post data;
- Create a json structure to be uploaded to the server;
- Create the NSURLSessionUploadTask that will download the data for us, calling in the end the completionHandler with the response, data or possible error;
As I told you from the beginning, this is really just a scratch on the surface of NSURLSession and it’s entire potential. I hope your appetite for deeper knowledge on iOS development and/or networking libraries is now insatiable and growing.
If you’re having a hard time finding resources to help you or you simply would like to share your next awesome idea with me, it will be a pleasure to hear you out!
Originally published at https://blog.codavel.com.