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.

Covid 19
COVID-19: Digital Insights For Enterprise Action

Access Perficient’s latest insights into how you can leverage digital technologies to not only respond to the pandemic, but drive your operations forward and deliver experiences your customers need.

Get Informed

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: “… “)!)
//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
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)”)

About the Author

More from this Author

Leave a Reply

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

Subscribe to the Weekly Blog Digest:

Sign Up