timbats1993 timbats1993 - 3 years ago 163
JSON Question

Getting API Data within Swift

I'm trying to get some data from an API at the address https://api.coinmarketcap.com/v1/ticker/bitcoin/?convert=AUD

I've started a new playground within Xcode, and my code is as follows

let urlString = "https://api.coinmarketcap.com/v1/ticker/bitcoin/?convert=AUD"

let url = URL(string: urlString)
URLSession.shared.dataTask(with:url!) { (data, response, error) in
if error != nil {
print(error as Any)
} else {
do {

let parsedData = try JSONSerialization.jsonObject(with: data!) as! [String:Any]
let id = parsedData["id"] as! [String:Any]

print(id)

} catch let error as NSError {
print(error)
}
}

}.resume()


However the playground is returning no result. I am quite new to Swift, so some of the syntax may be a little off. Can anyone make a suggestion how to obtain the information obtained at the API address?
Thanks!

Answer Source

You need to import PlaygroundSupport and set needsIndefiniteExecution to true.
Also you have some errors in the code as the result is array and you are casting it into a dictionary [String : Any].
Use the following code:

import UIKit
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

let urlString = "https://api.coinmarketcap.com/v1/ticker/bitcoin/?convert=AUD"

let url = URL(string: urlString)
URLSession.shared.dataTask(with:url!) { (data, response, error) in
    if error != nil {
        print(error!.localizedDescription)
    } else {
        do {

            let parsedData = try JSONSerialization.jsonObject(with: data!) as! [[String : Any]]
            for item in parsedData
            {
                let id = item["id"] as! String
                print(id)
            }

        } catch let error as NSError {
            print(error.localizedDescription)
        }
    }

    }.resume()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download