Reputation: 101
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?
Upvotes: 2
Views: 6041
Reputation: 1
extension ViewController {
func userDetail() {
let url = URL(string: getApiUrl)!
let session = URLSession.shared
var request = URLRequest(url: url)
request.setValue( "Bearer \(userToken)", forHTTPHeaderField: "Authorization")
let task = session.dataTask(with: request) { (data, response, error) in
if let error = error {
print (error)
} else if let data = data {
do {
let decoder = JSONDecoder()
let responseDatas = try decoder.decode(InstaStory.self, from: data)
DispatchQueue.main.async {
self.datas = responseDatas.data.tagPost
self.collectionView.reloadData()
}
} catch {
print(error)
}
} else {
print("something went wrong")
}
}
task.resume()
}}
Upvotes: -2
Reputation: 1
extension ViewController {
func getApi() {
let url = URL(string: getApiUrl)!
let request = URLRequest(url: url)
let session = URLSession.shared
let task = session.dataTask(with: request) { (data, response, error) in
if let error = error {
print(error)
} else if let data = data {
do {
let decoder = JSONDecoder()
let response = try decoder.decode(Birthday.self, from: data)
print(response)
print(response.name)
DispatchQueue.main.async {
self.getApiUrl = response
}
}
} catch {
print(error)
}
} else {
print("something went wrong")
}
}
task.resume()
}
}
Upvotes: -2
Reputation: 1824
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()
Upvotes: 1