Write Your Own API Manager for iOS

We are going to write API manager for iOS which uses URLSession. URLSession is suitable for handing HTTP/HTTPS requests. I used to depend on third-party libraries like “Alamofire” or “AFNetworking”. We are going to create the API Manager class using NSURLSession. Which is fairly simple and easy to implement.

Photo by NordWood Themes on Unsplash

datatask: Data task requests a resource and server returns objects as NSData.

downloadtask: Download task, download a resource directly to file in the disk.

uploadtask: Use this task to upload a file from disk to a web service with HTTP POST or PUT method.

There are 3 types of session configurations are available.

  • default: Creates a default configuration object that uses the disk-persisted global cache, credential, and cookie storage objects.
  • ephemeral: Similar to the default configuration, except that all session-related data is stored in memory. Think of this as a “private” session.
  • background: Lets the session perform upload or download tasks in the background. Transfers continue even when the app itself is suspended or terminated by the system.

URLRequest consists of an HTTP method (GET, POST, etc) and the HTTP headers.

Create a function for handling the network request with parameters request, HTTP method. In this method, we are setting the http method for the request. After we create a default URLSessionConfiguration. Then initiate a data task with the request.

Now we have created network-manager then we will call the data request with HTTP GET method. I am calling API with HTTP GET method.

Similarly, we can make an HTTP POST request using the same method.

Source code available on GitHub: https://github.com/rintoandrews90/NetworkManager

Thanks for reading 🙌🏼

--

--

iOS Developer

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