How to make an HTTP request on iOS App using Swift?


To make an http request in iOS we’ll make use of DataTask and sessions. We’ll create configuration, sessions, url, request, and dataTask objects. Let’s see the steps that we’ll go through.

The HTTP request can be of different types, it depends on what kind of request we want to make to our server. Below are the basic types of requests.

“GET”,”POST”,”PUT”,”DELETE” , we can make use of any of these according to our API. The basics remain same for each kind of request, which are shown below. Let’s see these examples with DELETE type of request.

  • First of all we need to create a session object, which default configuration.

let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration)
  • Then we need to create an URL Request of The type we need, it can be get, post, delete or put. In this example we are seeing ”Delete” type.

let url = URL(string: URLString)
//let url = NSURL(string: urlString as String)
var request : URLRequest = URLRequest(url: url!)
request.httpMethod = "DELETE"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
  • Once we have created the request object, we need to perfrom dataTask, with URL we just created above. This is how our complete dataTask method should look like now.

let dataTask = session.dataTask(with: url!) { data,response,error in
   guard let httpResponse = response as? HTTPURLResponse, let receivedData = data
   else {
      print("error: not a valid http response")
      return
   }
   switch (httpResponse.statusCode) {
      case 200: //success response.
         break
      case 400:
         break
      default:
         break
   }
}
dataTask.resume()
  • Now we can embed this in a function and use in our code.

hitAPI(_for URLString:String) {
   let configuration = URLSessionConfiguration.default
   let session = URLSession(configuration: configuration)
   let url = URL(string: URLString)
   //let url = NSURL(string: urlString as String)
   var request : URLRequest = URLRequest(url: url!)
   request.httpMethod = "DELETE"
   request.addValue("application/json", forHTTPHeaderField: "Content-Type")
   request.addValue("application/json", forHTTPHeaderField: "Accept")
   let dataTask = session.dataTask(with: url!) { data,response,error in
      // 1: Check HTTP Response for successful GET request
      guard let httpResponse = response as? HTTPURLResponse, let receivedData = data
      else {
         print("error: not a valid http response")
         return
      }
      switch (httpResponse.statusCode) {
         case 200:
            //success response.
            break
         case 400:
            break
         default:
            break
      }
   }
   dataTask.resume()
}

Note: You may need to allow Transport Security exceptions in your info.plist file to access some APIs.

There is no output shown with this example as an API is required to delete some data.

Updated on: 30-Jul-2019

663 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements