0

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") ..........

1 Answer 1

1

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") 
                             .......
                           })
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.