Network Request and Accessing REST APIs in iOS App

Introduction

When you want to support dynamic content and sync the data from one device and also access it from anywhere on the Internet via the website or other cloud accounts, then the developers need to build the systems that integrate with the server-side implementations.

In this blog, the discussion will be on the basics of client-server networking architecture, by accessing REST APIs with Postman or Advance rest-client tools. We will see how an iOS app can request the data from the cloud and send and update the data to the cloud with the Apple Networking Frameworks.

The following topics are to be covered:

  • REST architecture
  • Connection reachability
  • URLSession

Objective

After going through this blog, you will be able to understand the communication and data transfer between the client-side app and server which will help you to identify the user accounts across multiple clients with credentials that can share the data with the server and vice versa as well.

1. REST architecture

REST is the acronym for Representational State Transfer, which is the architecture for the hypermedia systems used for portability of the user interface data across multiple platforms. Application Programming Interface (API) is a set of protocols and definitions used for service request contract between the information provider and the information consumer, and work as a middleman for the webserver content and content consumer client.

An iOS app development can implement the client request for RESTful APIs, which will enable the app to handshake successfully with the server securely and further the data and get the content for the end user consumption.

2. Information content type

When we require using RESTful APIs, the communication content needs to be defined such that the client and the server can parse and understand the data easily. The Content Types of APIs are as follows:

  • JSON: JSON is the most popular content type in client requests due to its lightweight structure, and it is easily readable by both humans as well as machine algorithms.
  • XML/XSLT: XML stands for eXtensible Markup Language. It was created as a language with the basic formal syntax, making it straightforward for both the programs and the people to produce and manipulate the documents with a focus on Internet use.
  • Binary File: The Binary file is used when there is a need to send a file attachment with the text information in an API request.
  • Plain Text: Plain text can be sent when there is no need for structured data and is used very rarely in the context of the best API communication.

3. HTTP structure

Data is transferred between a server and a client via HTTP messages. There are different kinds of messages – requests, which are delivered by the client to cause the server to act, and responses, which are the server’s responses. The HTTP messages are made up of textual data encoded in ASCII. The HTTP Structure consists of mainly two components-one is a Request and the other is a Response. The HTTP requests are messages sent by the client to initiate an action on the server. The request target, usually a URL, or the absolute path of the protocol, port, and domain are usually characterized by the request context.

4. Request Methods

HTTP specifies a variety of request methods for expressing the desired action for a given resource. These request methods are frequently referred to as HTTP verbs. Each of them implements a different semantic, although a number of them have certain similar properties. The list of HTTP methods is as follows:

  • GET: The GET method is used to get a representation of a resource. Requests made using the GET method should only return the data.
  • POST: The POST method is used to submit an entity to the given resource, which frequently causes the server’s state to change or have side effects.
  • PUT: All existing representations of the target resource are replaced with the request payload when using the PUT method.
  • DELETE: The DELETE method removes the provided resource from the system.
  • CONNECT: The CONNECT method creates a tunnel between the client and the server specified by the destination resource.
  • TRACE: A message loop-back test is performed via the TRACE technique along the way to the target resource.

The client in the form mobile app makes the API requests with one of the request methods stated above to the Application server which validates the request and saves it to the storage as well as sends back the data to the client, as shown:

5. HTTP headers

The HTTP headers allow the client and server to send extra data with an HTTP request or response. The name of an HTTP header is case-insensitive, followed by a colon (:), and then the value. The headers can be grouped mainly into the following four types:

  • Request– The client seeking the resource can be found in the request headers.
  • Response– Information like location or the server that sent it is stored in the response headers
  • Representation– The representation headers provide information about the resource’s body, such as the MIME type or the encoding/compression used.
  • Payload– The Payload headers provide the representation-agnostic information on the payload data, such as the content length and transport encoding

6. HTTP body

The body of the request is the final component. The requests that fetch the resources, such as GET, HEAD, and DELETE, often do not require one. Some requests, such as POST requests, transmit the data to the server to update it. The two headers, Content-Type and Content-Length, describe the single-resource bodies, which are made up of a single file. Multiple-resource bodies are made up of several parts, each of which contains a distinct piece of information. The HTML Forms are commonly connected with this.

Connection reachability

When we are required to establish a connection with a server with RESTful APIs for handling and managing the user information, the mobile devices must work properly with the Internet connection. The connections lost in between or before the API calls may cause several issues to your app. For this, we need to check for the Internet connection reachability as well as our server reachability. There might be cases where the Internet connection would work perfectly but the server might be down. To check the Internet and the server connection, we will write a class named Reachability, which is as follows:

import Foundation

import SystemConfiguration

The reachability class can have a class function that will check for the connection to the Internet reach concerning the socket flags status. Let’s understand the given example in detail, as follows:

  • With the use of the SystemConfiguration framework, we will first create a socket address that contains the IP information while connecting to the network.
  • Further, SCNetworkReachabilityCreateWithAddress returns an object which creates a network establishment. If these operations failed to create a network reachability object, then we can return it, as there is no network available.
  • In some cases, we even get that object, but we need to ensure with appropriate flags whether the correct Internet connection is established or not.
  • In such cases, we check on SCNetworkReachabilityGetFlags to get the network status flags. If we get the reachable flag as true and the connection required flag as false, then we can confirm that an Internet connection is available.

A fast and reliable network connection makes your app efficient and fast to communicate with the server. But sometimes, there is a possibility of a down server; in such cases, we must communicate to the user with a proper server down message, so that the users do not get confused when the API starts to fail. Now, we will write another class function that checks for the establishment of the connection to your API server, as follows:

class func isServerConnect (websiteToPing: String?, completionHandler: @ escaping (Bool) -> Void) {

// 1. Check the Internet Connection

// 2. Check the Server Connection

In this class function, before requesting the server, we will first check for a successful Internet connection. Let’s understand the given example in detail, as follows:

  • After checking for the network connection, we can perform a check on whether the server is up or down and available for making the server-side requests.
  • Further, the URL request object is passed to the URL session singleton which makes a data task request.
  • When a data task request returns an error as nil with a properly handled response, the server connection is reachable.

URLSession

The URLSession class and its subclasses offer an API for receiving and uploading the data to URL-based destinations. This API may also be used by your program to execute the background downloads when it isn’t operating or, in the case of iOS when it is suspended. To handle the authentication and to receive events like redirection and task completion, use the associated URLSessionDelegate and URLSessionTaskDelegate. One or more URLSession instances are created by your program, each of which coordinates a collection of linked data-transfer activities.

Types of URL sessions

For the simple requests, URLSession has a singleton shared session (which does not contain a configuration object). It’s not as flexible as the sessions you design, but it’s the right place to start if you only have a few needs. The shared class function is used to access this session. Create a URLSession with one of the three settings for the different types of sessions, shown as follows:

  • A default session is similar to a shared session, but it allows you to customize it. You may also delegate the default session to a delegate to get the data progressively.
  • Ephemeral sessions are identical to the shared sessions except that they don’t save caches, cookies, or credentials to the memory.
  • While your program isn’t operating, the background sessions allow you to execute the content uploads and downloads in the background.

URLSessionConfiguration

When establishing a URLSession object to upload and download the data, a URLSessionConfiguration object sets the behavior and policies to employ. When uploading or downloading the data, the initial step is always to create a configuration object. This object is used to set the timeout settings, caching rules, connection requirements, and other information that will be used with the URLSession object. The type of configuration used to generate a URL session has a significant impact on the behavior and capabilities of the session. The default sessions function similarly to the shared sessions (until further customized), except that they allow you to access the data progressively via a delegate. The default method on the URLSessionConfiguration class may be used to establish a default session setup, as shown as follows:

lazy var session: URLSession = {
let config URLSessionConfiguration.default
return URLSession(configuration: config, delegate: self, delegateQueue: nil)
}()

The Ephemeral sessions are identical to the regular sessions, except that they don’t save caches, cookies, or credentials to the disc. The ephemeral method on the URLSessionConfiguration class may be used to generate an ephemeral session configuration.

Types of URL session tasks

You may build the tasks within a session that uploads the data to a server and then receive the data from the server as a file on the storage memory or one or more NSData objects in the memory. There are four kinds of tasks available in the URLSession API, which are as follows:

  • NSData objects are used by the data activities to deliver and receive the data. The data tasks are designed for brief, interactive server queries.
  • The upload tasks are similar to the data tasks, in that they deliver the data and allow for the background uploads even when the app isn’t open.
  • While the program isn’t operating, the download tasks retrieve the data in the form of a file and allow the background downloads and uploads.
  • The WebSocket tasks use the RFC 6455 defined WebSocket protocol to send and receive the messages via TCP and TLS.

URLSession delegate

A common delegate object is shared by all the tasks in a session. This delegate is used to offer and collect the information when certain events occur, such as the following:

  • When the authentication fails.
  • When the data arrives from the server.
  • When the data becomes available for caching.

Using the methods described in URLSessionTaskDelegate, each task you create using the session calls back to the session’s delegate. By writing a separate task-specific delegate, you may intercept these callbacks before they reach the session delegate, as follows:

When your app wants to upload large files to the server destination, there is a need for the output stream and the input stream with a buffer to upload the file’s byte data with the help of the URLSession upload task, as shown in the figure:

App transport security

App Transport Security (ATS) is a networking feature on the Apple platforms that enhances the privacy and data integrity of all the applications and app extensions All HTTP connections established with the URL Loading System using the URLSession class must use HTTPS, according to ATS. It also applies typical security tests on top of the Transport Layer Security (TLS) protocol’s default server trust evaluation. The connections that do not satisfy the minimum security requirements are blocked by ATS.

Conclusion

The communication of the app clients from the server with the help of REST APIs gives enhanced capabilities to the app developers to sync with the other client’s data, and stream the data from the devices to the server backend. Sometimes, you may need to implement a third-party library and its data to showcase on your app after the authentication, which would also require similar capabilities which we discussed in this blog in detail.

Alamofire is an advanced-level library that hides all the difficult steps for you and gives an advanced performance with cache handling, proper data handling, image downloading, error handling, file data management, etc. Although Alamofire takes care of the no Internet and server not responding issue, it’s good to handle it separately, as discussed initially.

Swarup Kr

Swarup Kr Saha is a Senior Technical Analyst cum Corporate Trainer. He is seasoned and successful in creating fresher’s training programs for the IT aspirants and helping them excel in their careers. An enthusiast in IoT, he has more than 10 years of experience. He believes in a continuous learning procedure and is committed to providing Quality Training in the areas of ABCD (Application Development, Big Data, Cloud and Database). Using his exemplary skills, he also develops Full-Stack Web and Mobile (Android & iOS) App connecting IoT with REST-API based solutions.