How to access RESTFul services from iOS/iPhone?


To access REST APIs in swift we need to go through a series of steps using the native way of networking in swift, that is using URL sessions and Data Tasks.

Rest stands for Representational State Transfer, which defines some set of constraints that are to be used by web services. In swift, we can access web services in the following way.

  • 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 get, post, delete or put. In this example, we are seeing ”GET” type.

let url = URL(string: URLString)
//let url = NSURL(string: urlString as String)
var request : URLRequest = URLRequest(url: url!)
request.httpMethod = "GET"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
  • Once we have created the request object, we need to perform 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 = "GET"
   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 get some data.

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jun-2020

84 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements