iOS
Request
Now that the iOS application has an authorization code
, it can exchange it for an access_token
required to make a request to a vehicle.
1. Obtain an access token
After receiving the authorization code
, the iOS application must exchange it for an access_token
. To do so, we can send the code
to the back-end service which will implement in a bit. Until then, let’s assume our back-end service contains an endpoint /exchange
that receives an authorization code
as a query parameter and exchanges it for an access_token
.
We can add this logic in our completion
callback -
// getting-started-ios-sdk/ViewController.swift
// TODO: Request Step 1: Obtain an access token
Alamofire.request("\(Constants.appServer)/exchange?code=\(code!)", method: .get)
.responseJSON {_ in}
Notice that our back-end service does not return the access_token
. This is by design. For security, our front-end should never have access to the access_token
and should always be stored in the back-end.
2. Get vehicle attributes
Once the backend has the access_token
, it can send requests to a vehicle using the Smartcar API. The iOS app will have to send a request to the back-end service which in turn sends a request to Smartcar. We have to do this because our front-end does not have the access_token
.
Assuming our back-end has a /vehicle
endpoint that returns the information of a user’s vehicle, we can make this query in our completion
callback and segue
into another view the returned vehicle attributes -
// getting-started-ios-sdk/ViewController.swift
func completion(err: Error?, code: String?, state: String?) -> Any {
// send request to exchange auth code for access token
Alamofire.request("\(Constants.appServer)/exchange?code=\(code!)", method: .get).responseJSON {_ in
// TODO: Request Step 2: Get vehicle information
// send request to retrieve the vehicle info
Alamofire.request("\(Constants.appServer)/vehicle", method: .get).responseJSON { response in
print(response.result.value!)
if let result = response.result.value {
let JSON = result as! NSDictionary
let make = JSON.object(forKey: "make")! as! String
let model = JSON.object(forKey: "model")! as! String
let year = String(JSON.object(forKey: "year")! as! Int)
let vehicle = "\(year) \(make) \(model)"
self.vehicleText = vehicle
self.performSegue(withIdentifier: "displayVehicleInfo", sender: self)
}
}
}
return ""
}
3. Back-end service
Now that our front-end is complete, we will need to create a back-end service that contains the logic for the /exchange
and /vehicle
endpoints.
Note: you can ignore the Try It Out section of the Getting Started guide, and instead follow along with the next section.
Try it out
Make sure your back-end server is up and running. In your back-end directory -
export SMARTCAR_REDIRECT_URI=sc + "clientId" + ://exchange
node index.js
Now run the iOS application in XCode!