Networking

This section is not endemic to Swift, but many of the topics presented here have specific Swift analogs that are important to understand.

Client Server Model

Networking allows you to connect your app to the internet. But what's the internet? The internet is actually also made up of a bunch of devices that talk with each other, forming a network of communication. There are many ways interpret the internet and this can be a course of its own. We will be focusing on the most common Client–Server model.

In iOS development the client will almost always be your app, and the server will be somewhere in the internet. However, with the vast number of clients and servers it will be utterly chaotic if each device communicates in their own way. This is where the Hyper Text Transfer Protocol (HTTP) comes in. It is a set of rules which the client and servers abide by in their communcation. A side note, there are actually many, many other protocols (see here) but we will be focusing on HTTP as its the most common and (I would say) important to know.

This communication happens in two parts.

  1. Request - this is sent by the client to ask the server for data, or inform the server of some event.

  2. Response - this is sent from the server back to the client as a form of reply to the client's request.

It is important to remember that only the client can initiate this communication (with a request).

HTTP Requests

HTTP requests come in many forms, but the following three are the most common (covering almost all your use cases).

  • GET - to retrieve or get data from the server

  • POST - to send data to server to create/update some model

  • DELETE - to tell the server to delete some model

Before we dive into more detail about each of these requests, let's first introduce the Uniform Resource Locators (URL)

Uniform Resource Locators (URL)

A URL is nothing more than the address of a given unique resource on the Web, similar to street addresses pointing to unique houses in the world. The following images breaks it down nicely

You can think of sending a HTTP request as sending a letter. You write the mailing address of your receipt on the envelope along with other basic information and you put your letter inside, then you send it off. Here, the domain and port would equivalent to the mailing address and the parameters would be the other basic information you write on the envelope. Regardless what the letter is about, the information on the envelope alone (information contained in the URL) is enough to find where to send the letter. But what about the letter...? We will get to that later!

GET Request

GET requests are generally used for retrieving data (though you can also send data with it). All the information about the request is located in parameters of the Request-URL. As a result, there is a restriction to the length of the request. These requests can be cached, bookmarked and will appear in your browser history (which is not as private as you think!). This can lead to issues with sensitive data since all the information about the request is in plain sight—akin to being written on surface of the envelope.

Imagine if Facebook handles user login with GET requests, it would look something like

https://www.facebook.com/login?user=JustinNgai&password=mySecretPassword;)

and that's quite problematic. It can also be an issue if the length of the data is restricted—what if my username is really long? To solve this we introduce POST requests.

POST Request

POST requests are generally used for sending data. Along with sending what's in the URL, it also sends a request body—the letter in the envelope. This request body is not restricted in length, not cached, not bookmarked and not stored in history 🎉. This makes it capable of sending large chunks of data and handling sensitive data.

HTTP Responses

When the server gets a requests, it processes it and sends back the appropiate data along with a response code.

A response code is a 3-digit code that encodes the result of the request. The first digit represents the category as seen below

And the next two digits correspond to a unique status which you can look up here. These are things you can always just look up but here are some common ones

  • 200 - OK (All good!)

  • 301 - Moved Permanently

  • 403 - Forbidden

  • 404 - Not Found

  • 500 - Internal Server Error

Not that we've covered the requesting and responding, we can finally focus on the actual data being sent—the letter!

Say for example you build a restaurants app in Swift and you create a Restaurant.swift model. You now want send data stored in your Restaurant model to the server. How do you accomplish this? This problem of serialization is where JavaScript Object Notation (JSON) comes in handy.

JSON (JavaScript Object Notation)

JSON is a popular way to store and transport data. The main idea is that the client takes the data it wants to send and turns it into a JSON format (which is then serialized i.e turned into a string). This is sent as the body of the request (the letter in the envelope). The server, upon receiving the string, will deserialized it and extract the JSON. The server can then process the data as it sees fit. This is illustrated below

Client Model => JSON => String => ... => String => JSON => Server Model

This also works in reverse i.e in the responding process

Server Model => JSON => String => ... => String => JSON => Client Model

Like this the client and server models can be wildly different but they can still communiate with a common form of data transmission format—JSON.

JSON Types

{
    "name": "Intro to iOS Development",
    "number": 1998,
    "instructors": [
        {
            "name": "Justin Ngai",
            "netid": "jn537"
        },
        {
            "name": "Noah Pikielny",
            "netid": "np299"
        }
    ]
    "isFun": true
}

JSONs store data in key value pairs. Above is a sample JSON. The key must be a string, but the value can be any of the following:

  • Strings

  • Numbers

  • Arrays

  • Booleans

  • Null

  • JSON objects (can be nested)

And that's the basics of networking. In the next chapters we will cover how we send requests, and process responses in our iOS apps!

Last updated