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

iOSMobile DevelopmentiPhone/iPadSwift

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.

  • 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 ”POST” type.

let url = URL(string: URLString)
//let url = NSURL(string: urlString as String)
var request : URLRequest = URLRequest(url: url!)
request.httpMethod = "POST"
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.

func 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 = "POST"
   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 post some data.

raja
Published on 18-Apr-2019 09:56:28
Advertisements