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 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 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;
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 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!