从回调函数swift获取价值

时间:2017-09-29 15:24:51

标签: swift

问题我想获取从我的ApiToken函数返回的值,以便我可以在另一个函数中使用它。由于某种原因,我无法从此函数中获取值,它不会返回任何内容。我怎么能从我的ApiToken函数返回值并在另一个函数中使用它。

这是我的带有ApiToken函数的GetApiToken类

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()
    }
}

这是我试图获取值

的地方
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 个答案:

答案 0 :(得分:1)

它是一个异步调用,所以你需要把完成回调中检索到数据后发生的一切都放在

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