Software Development

HandsOn: Using NSURLSession

HandsOn: Using NSURLSession

I recently had to explore the iOS HTTP libraries landscape, since we're doing everything we can to make the developer’s life easier when using Bolina. I had to understand the usage of each one of them among the community, but I also wanted to experience the “true pain” of using an iOS native networking library. That's why I created this demo project.

In this hands-on session we will scratch the surface of using NSURLSession, the native iOS modern API for networking, and its usability 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:

  1. Define the NSURLSession that you will use. You can create one or use one of the available like the shared session;
  2. Specify the resource URL you want to download;
  3. Create the NSURLSessionDataTask that will download the data, calling in the end the completionHandler with the response, data or possible error;
  4. 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;
  5. 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:

  1. Define the NSURLSession that you will use. You can create one or use one of the available, like the shared session;
  2. Specify the request to post data;
  3. Create a json structure to be uploaded to the server;
  4. 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 an 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!