iOS Networking with Swift

We will begin with the networking foundations to understand web services.

Kaan Vural
3 min readJun 29, 2020

Clients can connect to the related server by using URL which contains;

https:// — SCHEME = specifies how to connection will happen.
* HTTP is a protocol for transferring hypertext documents on the World Wide Web. HTTPS is secure(encrypted data flow) version of HTTP.

medium.com/ — HOST = gets our request to the right computer

@vuralkaan/PATH = our end point

But the URL can contain below items;

scheme:[//[user[:password]@]host[:port]][/path][?query][#fragment]

Therefore, DNS will help to determine the actual IP address of the server.

Let’s say we are going to use Dog API in our application. And we have

let urlString: = “https://dog.ceo/api/breeds/image/random"

URL to get a random image. We need to get our string to be converted into an URL. In swift, we are able to do that any string by using

let url = URL(string: urlString)

But more precisely, We need to use URLComponents as below;

var urlComponents = URLComponents()

urlComponents.scheme = “https”

  • We can add all items as we mentioned above. (host, path, query…)

We may also use add items to any url by using appendPathComponent() method. URLComponent is able to separate url as in query, host, path …

To make a network request we use URLSession object which provides shared property. (singleton)

URLSession calls ‘request’ : TASK

  • DataTask: Returns data from the network directly into memory as instance of the datastruct.
  • DownloadTask: Works like DataTask except the data is stored directly in a file on the device.
  • UploadTask: To upload a file to any server.
  • StreamTask: To get a continuous stream of data from a server.

After creating task we need to start this task by calling resume()

If we are going to use data coming from HTTP; App Transport Security blocks data coming from HTTP. In reality, some servers still use HTTP.

We need to create a key as below in info.plist

API gives you the map of what the method looks like. Web service can contain multiple APIs.

JSON is a data format often used to send data to and from web service.

There are 2 ways to handle JSON data in iOS.

  • JSON Serialization
  • Codable

JSON Serialization

Converts JSON data to and from swift dictionaries. The JSON object is treated as a dictionary.

  • You need to map all the keys manually
  • You need to translate all to fit into a dictionary

Codable

The data is converted into a struct where you can then extract individual values. Codable is a way more modern approach. Codable even lets you convert between swift types and other formats such as XML or a custom type.

  • Directly matching
  • If the JSON’s and our struct’s property names are not equal(like if we want to use in a different name), we need to use CodingKeys to map all parameters to the related field.

--

--