Snowman08
Snowman08

Reputation: 425

Get value from callback function swift

Question I want to get the value returned from my ApiToken function so I can use it in another function. For some reason I can not get the value from this function it will not return anything. How could I return the value from my ApiToken function and use it in another function.

Here is my GetApiToken class with the ApiToken function

class GetApiToken {



    public func ApiToken(link: String,  completionBlock: @escaping (String) -> Void) -> Void
    {
        let url = URL(string: link)!
        let jsonDict = ["username": "snow", "password": "ssssssssss"]
        let jsonData = try! JSONSerialization.data(withJSONObject: jsonDict, options: [])

        var request = URLRequest(url: url)
        request.httpMethod = "post"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpBody = jsonData

        let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
            if let error = error {
                print("error:", error)
                return
            }

            do {
                guard let data = data else { return }

                guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: AnyObject] else { return }

                //self.token = json["access_token"] as? String ?? "x"
                completionBlock((json["access_token"] as? String)!)



            } catch {
                print("error:", error)
            }
        }

        task.resume()
    }
}

Here is where I am trying to get the value

func getData(_ link:String)
    {
        let url = URL(string: link)!
        var request = URLRequest(url: url, cachePolicy: .reloadIgnoringCacheData, timeoutInterval: 20)
        request.httpMethod = "GET"
        var output = ""
        GetApiToken().ApiToken(link: "http://localhost:5000/auth", completionBlock: { str in
            output = str

        })
        request.addValue("JWT  \(output)", forHTTPHeaderField: "Authorization")
        request.setValue("application/json", forHTTPHeaderField: "Content-Type") ..........

Upvotes: 0

Views: 267

Answers (1)

XmasRights
XmasRights

Reputation: 1509

It's an asynchronous call, so you need to put everything that will happen once the data has been retrieved in the completion callback

func getData(_ link:String)
{
    let url = URL(string: link)!
    var request = URLRequest(url: url, 
                             cachePolicy: .reloadIgnoringCacheData,
                             timeoutInterval: 20)
    request.httpMethod = "GET"
    GetApiToken().ApiToken(link: "http://localhost:5000/auth", 
                           completionBlock: 
                           { output in
                             request.addValue("JWT  \(output)", forHTTPHeaderField: "Authorization")
                             request.setValue("application/json", forHTTPHeaderField: "Content-Type") 
                             .......
                           })

Upvotes: 1

Related Questions