I have an JSON that comes from an API. I need to show as a text a value from it.
This is a piece of it.
]
{
"d": "2019-09-20",
"v": 56.62
},
{
"d": "2019-09-23",
"v": 56.93
}
]
Now, I created the model for it, called Dolar.swift.
struct Dolar: Decodable {
var d: String?
var v: Double?
}
And also a class called WebService.swift that will handle the call:
class WebService {
func getCurrency(completion: @escaping (Dolar?) -> ()) {
guard let url = URL(string: "https://api.estadisticasbcra.com/usd_of") else { return }
URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let data = data, error == nil else {
return
}
let currencyResponse = try? JSONDecoder().decode(Dolar.self, from: data)
if let currencyResponse = currencyResponse {
let dolar = currencyResponse
print(dolar)
completion(dolar)
} else {
completion(nil)
}
}.resume()
}
}
The documentation from the API says it requires a TOKEN be added to the request:
Authorization: BEARER {TOKEN}
How do I do that? I have the TOKEN, but don't know how to implement it. That's my first question.
Second, once I get the value, how do I show it on the ContentView.swift?
Any help is appreciated.
errorDolar, then the decode statement should beJSONDecoder().decode([Dolar].self, from: data), but your completion expects a singularDolarso there is some confusion that needs clearing up.