Calling APIs using Playground

September 2, 2018 ยท 2 minute read

I had a need to test out calling an API, but didn’t want to create a new project. So here’s how to call one using Playground. Replace the URL with one you are working on and update the JSON serialization

//: Playground - noun: a place where people can play
// https://stackoverflow.com/questions/24058336/how-do-i-run-asynchronous-callbacks-in-playground
import UIKit
import PlaygroundSupport
import Foundation

// models
struct CarbonDioxideIndex
{
    var value: Float = 0        //  - carbon monoxide volume mixing ratio
    var pressure: Float = 0     // - atmospheric pressure at the point of measurement, hPa. Recommended for scientific use at pressure levels between 215 and 0.00464 hPa
    var precision: Float = 0    //- measurement precision
    var timeStamp: String = ""  // ISO 8601 timestamp format
}


// resolve path errors
URLCache.shared = URLCache(memoryCapacity: 0, diskCapacity: 0, diskPath: nil)

PlaygroundPage.current.needsIndefiniteExecution = true

// encapsulate execution completion
func completeExecution() {
    PlaygroundPage.current.finishExecution()
}

let urlString = "https://api.openweathermap.org/pollution/v1/co/50,-122/current.json?appid=XXXXXXXX"

let url = URL(string: urlString)!

let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
    guard error == nil else {
        print(error?.localizedDescription ?? "")
        return
    }
    
    if let data = data, let contents = String(data: data, encoding: String.Encoding.utf8)
    {
        do {
            let json = try JSONSerialization.jsonObject(with: data, options: []) as! [String: AnyObject]
            if let timeStamp = json["time"] as? String
            {
                print("Timestamp: \(timeStamp)")
            }
            
            if let carbonDioxideDict = json["data"] as? [[String:AnyObject]]
            {
                print("\n\nCarbon Monoxide data: \(String(describing: carbonDioxideDict.first))\n\n")
            }
        } catch let error as NSError {
            print("Failed to serialize data to json: \(error.localizedDescription)")
        }
        print(contents)
        completeExecution()
    }
}
task.resume()

Subscribe to my email list for a monthly newsletter and special updates!