iOS Networking with Swift

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

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.

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

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

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

Software engineer @huawei , musician

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store