Skip to main content

Integration & IT Modernization

Swift 3 – Quick and Dirty API Request to Test JSON Data in Xcode/iOS

At this point the UI is developed, we’re binding the “Pulse” text to our controller “Received Actions” graph_steps function, based on “Pulse” tap on the screen.

This code is an easy way to get started with testing a new API endpoint when the data is incoming. By no means is it a “best practice”, but this allows you to get up and running with various API endpoints. The assumptions are below. We already grabbed a token from either Postman or an API Explorer portal. See comments in the code.

You can follow my next post for the proper OAUTH 2.0 / Token implementation, but in the meantime Ray Wenderlich has great tutorials to follow

 

@IBAction func graph_steps(_ sender: AnyObject) {
var request = URLRequest(url: URL(string: “https://api.endpoint.com/… “)!)
print(request)
//You can pass any required content types here
request.httpMethod = “GET”
// Some bad practice hard coding tokens in the Controller code instead of keychain.
let access_token = “my_token”
//You endpoint is setup as OAUTH 2.0 and we are sending Bearer token in Authorization header
request.setValue(“Bearer \(access_token)”, forHTTPHeaderField: “Authorization”)
let session = URLSession.shared
session.dataTask(with: request) {data, response, err in
do{
let JSON = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary
let dataSet = (JSON.value(forKeyPath: “parentNode-childNode”) as! NSArray).object(at: 0) as! NSDictionary
DispatchQueue.main.async {
let Val = dataSet.value(forKey: “subChildNode”)
// This is specific to the graph UI that is used, and requires CGFloat type.
//currentSteps is my graph UI.
self.currentSteps.setValue(Val as! CGFloat, animateWithDuration: 1)
}
}
catch {
print(“json error: \(error)”)
}
}.resume()
}

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Arvin Karibasic

More from this Author

Follow Us