How to Handle Networking in iOS

How to Handle Networking in iOS

There are some fundamental skills worth knowing, one of them is to fetch data from an API. Consuming APIs in your iOS application can be intimidating and though there are numerous ways to achieve the same, maintaining them can be a bit tricky and overwhelming.

Networking Basics

When making request there were two computers that need to talk to each other.


Clients connect to the server by the help of web address (uniform resource locator) and the way these computers communicate is through Hyper Text Transfer Protocol or HTTP. As we send HTTP request we receive HTTP response via status code.

We generate hopeful response in 200’s which indicate success, when we get error from client side it show's 400’s and for server side it's 500’s.

HTTP verbs allow us to perform different operations with data on the server just like that were different action you perform in an app. Basic Operations on a website or database fall under the acronym CRUD (Create Read Update Delete), we will use the following HTTP verbs to create HTTP requests specific to each king of task.


URL & URL Components

Creating URL in swift using URL ->


Creating URL in swift using URL Components ->


URL Session & Data Tasks

To make network request in iOS, we use the URL Session object. URL Session: An object that coordinates a group of related network data transfer task. URL Session provides the shares property an object that can be used throughout your app. (URLSession.shared). When we say request, URL Session calls task or URLSession tasks.

Types of URL Session Tasks (Request) :

  • URL Session Data Task: Returns data from the network directly to the memory as a instance of the data struct. Data, its just a type in Swift that stores raw data or bytes.

  • URL Session Download Task: Works likes Data task, except that the data is stored directly in a file on the device. We use the download task when loading large files from the network that we don’t necessarily need to store in memory while our app is running.

  • URLSession Upload Task: is used for uploading data or sending a large amount of data from the device to the server.

  • URL Session Stream Task: a way to load continuous stream of data over the network accessing the music or videos file from a server are just some example of when you want to use a stream task,

Lets make our first request using URL Session, suppose we have a image url and we have to fetch the image and show it into UIImageView.


Here, task.resume() is responsible for making the request, this is how we make request using URL Session.

Parsing JSON

A data format often used to send data to and from web services. It provides a syntax or set of rules for storing text.


The braces and everything contained between them is a JSON Object. These object has properties like key (type) and value (colonial), separated by colons. Key-value are separated by colons. JSON object can store different types of value such as string, int, float, and boolean, similar to swift dictionary.

The process for getting values of the JSON is called parsing and we could parse the JSON data into such as converting to a dictionary or even into a custom struct.

JSON Serialisation (traditional method for parsing JSON in iOS apps), converts JSON data to and from swift dictionary. Codable (modern approach || Swift 4 introduced this Protocol). The data is first converted into a struct where we  can extract individual values. A protocol used to convert data like JSON and from Swift types.

SERAILISATION VS CODABLE: The old way to do JSON parsing in iOS was using JSON Serialisation and using this we have to map out all of the keys manually yourself. So we have to translate all of it into a dictionary and then know where the keys were and how they mapped out. But with the new codable protocol, as long as you create object that adheres to the protocol and has all of the properties that directly matches to the JSON, rest apple will work.

This is how we make request and decode data ->


Networking using Alamofire

Alamofire is an elegant and composable way to interface to HTTP network requests. It builds on top of Apple’s URL Loading System provided by the Foundation framework. At the core of the system is URLSession and the URLSessionTask subclasses. Alamo fire wraps these APIs, and many others, in an easier to use interface and provides a variety of functionality necessary for modern application development using HTTP networking.

Network call using Alamofire.

Networking using Moya

You probably use Alamofire to abstract away access to URLSession and all those nasty details you don't really care about. But then, like lots of smart developers, you write ad hoc network abstraction layers. They are probably called "APIManager" or "NetworkModel", and they always end in tears.

Moya is a network abstraction layer. It uses Alamofire and provides us to set up a network manager quickly.

Moya - GitHub

Steps to use Moya in your application ->

Step 1

Create Service for your API. I am using Dota Heros API for this example.

In Service we basically define our:

  • baseURL: Contains the base URL of an API.
  • path: Path of the URL.
  • method: CRUD method which we going to apply on an API.
  • task: We define the request parameters requried by the API.
  • headers: Headers requried by the API such as API key, refresh token, etc.


Step 2

Finally now we call an our API. We first define our MoyaProvider of our service, then by using that provider we request Moya for the response. Here, HeroModel is the struct Model for an API response data.


By using this completion we can easily access the response.