如何保存 CompletionHandler 返回的值?

Posted

技术标签:

【中文标题】如何保存 CompletionHandler 返回的值?【英文标题】:How can I save the value returned for an CompletionHandler? 【发布时间】:2016-10-30 22:44:02 【问题描述】:

我有下一个函数,它使用完成处理程序发出 http 请求并接收 json 响应:

func makeRequest3(request: URLRequest, completion: @escaping (JSON!)->Void)
    let task = URLSession.shared.dataTask(with: request) data, response, error in
        //Code

        print(data as NSData)
        let json = JSON(data: data)

        completion(json)

    
    task.resume()

我需要调用此函数,并找到“id_token”字段以将其保存在变量中。我是初学者,我正在尝试这段代码,但我有错误“类型'()'没有下标成员”

    var response2 =  makeRequest3(request: request) response in //<-`response` is inferred as `String`, with the code above.
        return(response)
    

    var idtoken = response2["id_token"]

我该怎么做?我正在使用 swift3。

【问题讨论】:

您不能使用return,因为请求将异步完成。您需要使用 inside 闭包中的令牌来完成您的工作。 【参考方案1】:

您的makeRequest3 本身不返回值,而是将响应传递给完成处理程序,在完成处理程序中完成响应所需的所有事情

makeRequest3(request: request) response in //<-`response` is inferred as `JSON`, with your `makeRequest3`.
    var idtoken = response["id_token"]
    //Use `idtoken` inside this closure
    //...

【讨论】:

以上是关于如何保存 CompletionHandler 返回的值?的主要内容,如果未能解决你的问题,请参考以下文章

使用 CloudKit 保存尝试对成员“保存(_:completionHandler :)”的模糊引用

Swift4中的completionHandler返回字符串

嵌入函数返回值后在函数中调用completionHandler?迅速

从 NSURLSession completionHandler 返回数据

GCD NSURLSession completionHandler 块返回值 null

completionHandler 的响应为零