General Middleware

API Call in IOS using SWIFT

Step1. Create the url, request and session 

//This is the API URL

let url = URL(string: “http://datamall2.mytransport.sg/ltaodataservice/TaxiStands”)

//Here you create the request

let request = NSMutableURLRequest(url: url!)

// This is where you enter the API Key that you get from the API Provider. The header name can be AccountKey or something else. Check the API Provider’s documentation to get that.

request.addValue(“XXXXXXXX”, forHTTPHeaderField: “AccountKey”)

//Set the http method “GET”, “POST”, “OPTIONS”, “PUT” etc.

request.httpMethod = “GET”

//This gives a singleton instance of the session, so that wherever you call, you get the same instance of the class

let session = URLSession.shared

Step2. Fetch the Response and Parse the JSON Data

let task = session.dataTask(with: request as URLRequest) { (data, response, error) in

    if data != nil {

        //Processing the data

        do {

            let jsonResponse = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers)

            if let rawRes = jsonResponse as? [String : Any] {

                if let dataArray = rawRes[“value”] {

                    if let acData = dataArray as? [Any] {

                        print(“acData = \(acData[0])”)

                    }

                }

            }

        } catch {

            print(“Something went wrong!!”)

        }

    }

}

Step 3. Fire the request

//Note that in all the above steps, you were just declaring or registering the different components. But this is where the request is triggered

task.resume()


Leave a Reply

Your email address will not be published. Required fields are marked *