1

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.

3
  • The decoding will not work regardless of if This is a piece of it. or not. Print the error Commented Sep 24, 2019 at 16:16
  • If the response is indeed an array of Dolar, then the decode statement should be JSONDecoder().decode([Dolar].self, from: data), but your completion expects a singular Dolar so there is some confusion that needs clearing up. Commented Sep 24, 2019 at 17:55
  • Sorry, I can't get the hand of this JSON decoding, could you help me out? If it helps, I only need the last object from the JSON (the last "d" and "v") but that may be a problem for another day. How can I decode this? Commented Sep 25, 2019 at 14:43

1 Answer 1

5

For the first part of your question, you need to use the variant of URLSession.dataTask which takes a URLRequest. Then you need to check the response had payload, that it can be decoded as your type and that it has at least one value in it. Something like:

let request = URLRequest(url: url)
request.setValue(token, forHTTPHeaderField: "Authorization")
// Or maybe:
// request.setValue("BEARER {\(token)}", forHTTPHeaderField: "Authorization")

URLSession.shared.dataTask(with: request) { (data, response, error) in
    guard let data = data else {
        return // Couldn't get data from service
    }

    guard let values = JSONDecoder().decode([Dolar].self, from: data) else {
        return  // Couldn't decode data as array of `Dolar`s
    }

    guard let finalValue = values.last else {
        return // No values in data
    }

    // `finalValue` now describes the last element in your array
}.resume()

See the docs for URLSession and URLRequest

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.