• 20 hours
  • Medium

Free online content available in this course.

course.header.alt.is_video

course.header.alt.is_certifying

Got it!

Last updated on 3/6/20

Understand Networking principles

Weโ€™ve got an app skeleton that can potentially offer lots of interesting content - except, we don't have any yet! The intended content is constantly changing, and thereโ€™s no reasonable way for us to put it within the application. We must get it from an outside source!

In order to communicate with the outside world, we need to implement whatโ€™s called networking.

What's networking?

Networking is simply managing a request-response combination over the network which is typically the internet.

Our code needs to send a request to some remote server following a specified format and wait for a response (or acknowledge a no-response).

Communicating with an external resource adds a layer of variability, or uncertainty, to our code. If it doesn't work as expected, there could be a fault in our code, or there could be something wrong with that external source.

Introducing Postman

To eliminate this layer, we are going to use another third-party service to test networking calls. One of the ones I recommend is Postman.  Postman communicates using networking calls - sending URL requests with parameters and receiving responses without having to write any code! ๐Ÿ˜‰

To start, download the app https://www.getpostman.com/apps. Under Postman for Mac, click Download. Then following the instructions. The download should start automatically. Once done, move the downloaded file - Postman - to the Applications folder on your computer and launch the app.

Here's what the initial screen looks like:

The initial screen of Postman
The initial screen of Postman

At the top, we have a field that allows us to enter a URL with or without parameters via HTTP/HTTPS with a desired communication method (GET, POST etc.). After clicking Send, the tool will send a request and will provide the response (or indicate the response timeout) in the bottom section of the app window.

We are going to try it out testing access to iTunes. We have two primary options available - search and lookup. Let's start with the lookup. This section lists some preset examples; we'll use the first one, which fetches the info associated with an artist by its ID -  https://itunes.apple.com/lookup?id=ID .

Let's look up The Beatles. (Hint - the ID is 136975). Paste the URL into the input at the top using GET method:

Look up GET request
Look up GET request

Click the Send button. We should get a response with the status  200 OK  and some data associated with the artist whose ID we specified as a parameter:

Lookup response
Lookup response

We can see by the result that this endpoint of the API we are trying to reach is working. Now let's play with a few variations, emulating an error on our part.

Providing an incorrect ID:

https://itunes.apple.com/lookup?id=1369750

Result:

Response with zero records
Response with zero records

Notice that we got no records in the response. However, the response status is still  200 OK  as the request/response combination is correct. There are simply no records found associated with the requested parameter.

Providing an invalid ID:

https://itunes.apple.com/lookup?id=1369750x

Result:

Respinse to bad request
Response to a bad request

Notice that this time, the server was not able to make sense of our request and along with an error response, we got a different response status:  400 Bad request .

Using an alternative method:  POST .

To supply the parameters, we need to enter them in the body section below the URL input:

POST method with parameters
POST method with parameters

Result:

{
"resultCount":1,
"results": [
{"wrapperType":"artist", "artistType":"Artist", "artistName":"The Beatles", "artistLinkUrl":"https://itunes.apple.com/us/artist/the-beatles/136975?uo=4", "artistId":136975, "amgArtistId":3644, "primaryGenreName":"Rock", "primaryGenreId":21}]
}

We've got the same result as using the GET method even though the API responds equally to both.

Which method should we use?

Technically, we are getting data and not posting it. The GET method is closer to the action we are performing; however, it requires appending all of the parameters to the endpoint URL and can have some of the following complications:

  • The url string can be long and cumbersome. 

  • It can be cached or bookmarked (this could be useful, unless we don't encourage it).

  • It exposes more details of an API functionality than necessary.

  • It's easier to hack.

In our example, we are going to use POST!

Using an incorrect endpoint:

https://itunes.apple.com/MY-lookup

Result:

404 - Not found response
404 - Not found response

And finally, what if we make a mistake in the server address altogether? ๐Ÿ˜ฑ

Incorrect server:

https://itunes.MY-apple.com/lookup?id=136975 

Result:

Incorrect server response (rather no response)
Incorrect server response (or no response)

Here we don't get any answer at all which makes sense - look at the address we typed. ๐Ÿ˜…

Look up call works well. What about search? Go ahead and experiment with the search endpoint. Start by using term parameter and feel free to experiment with others, i.e.:  https://itunes.apple.com/search?term=the+beatles  and other available parameters

Your turn now! ๐Ÿ˜ƒ

Done yet?!
You can do this!

Nicely done! ๐Ÿ˜Ž We are now certain the iTunes API is off the hook - it's working!

Networking in iOS with URLSession

Networking in iOS is very similar to other platforms. Thereโ€™s a set of objects in Swift that will help us prepare our app for getting the content we need!

We'll work with the following elements:

  • URLSession  - used to manage the whole session.

  • URLSessionConfiguration  - provides configuration for the session.

  • URLSessionTask  - responsible for performing a task.

  • and within that: 

    • URLRequest  - handling the request.

    • URLResponse  - handling the response.

The connections between the objects can be illustrated like this:

URLSession objects
URLSession objects

Configuring URLSession

URLSession  is initialized with  URLSessionConfiguration . This class is used to configure the session. To set it up, we need to answer some questions:

  • Do we accept cookies?

  • What's the cache policy?

  • What is the timeout of a query?

  • Do we have to add elements in the header?

  • Are there any other questions?

Launching a task

Once the URLSession is initialized with the correct configuration, it can launch a "task." A task starts a network request, receives the response, or decides to interrupt it, and so on. All that is handled by the  URLSessionTask  class which is responsible for managing the life cycle of the request.

There are several types of tasks which also include a subclass of URLSessionTask:

  • URLSessionDataTask  - used to send or receive data.

  • URLSessionUploadTask  - used to upload heavy files (video, audio recording, etc.) to a server.

  • URLSessionDownloadTask  - used to download heavy files (video, audio recording, etc.) from a server.

  • URLSessionStreamTask  - used to stream (continuous downloading).

Format of the response

After sending the request, the task object will form a response using the response from the server or deal with a no-response situation. In either case, the information is formatted using  URLResponse  class or its  HTTPURLResponse  subclass (specific to HTTP requests).

The first entry check count to analyze within this object is the status code of the response. It allows categorizing a high-level result - whether the request worked or an error occurred.

The response is also equipped with an object for potential error ( Error ) and data ( Data ). 

Nice work! ๐Ÿ˜Ž Next we are going to put this into practice!

Let's recap!

  • Networking is managing a request-response combination over the network.

  • iOS is now only supporting secure protocol - https (in other words, using http will not work).

  • Postman is a tool that allows you to test external APIs .

  • Even if multiple method options are supported by the server, GET for getting and POST for posting are more suitable and must be used.

  • To perform networking in iOS, the following classes are used:

    • URLSession - manages the entire session.

    • URLSessionConfiguration - provides configuration for the session.

    • URLSessionTask  - performs a task, with specific subclasses:

    •  URLSessionDataTask ,  URLSessionDownloadTask ,  URLSessionUploadTask ,  URLSessionStreamTask.

    • URLRequest - handles the request.

    • URLResponse  - handles the response. 

Ever considered an OpenClassrooms diploma?
  • Up to 100% of your training program funded
  • Flexible start date
  • Career-focused projects
  • Individual mentoring
Find the training program and funding option that suits you best
Example of certificate of achievement
Example of certificate of achievement