【问题标题】:Swift: completion handler after network requestSwift:网络请求后的完成处理程序
【发布时间】:2020-09-13 15:52:10
【问题描述】:

我知道,关于 Swift 中的异步函数和完成处理程序有很多类似的线程......但是在阅读了很多之后,我仍然无法弄清楚如何处理网络请求的响应数据和将某些值保存在全局变量中。

这是我的代码(是的,我是 Swift 菜鸟):


let equitySymbol = "AAPL"
var companyCountry = String()

func sendRequest(_ url: String, parameters: [String: String], completion: @escaping ([String: Any]?, Error?) -> Void) {
    var components = URLComponents(string: url)!
    components.queryItems = parameters.map { (key, value) in
        URLQueryItem(name: key, value: value)
    }
    components.percentEncodedQuery = components.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")
    let request = URLRequest(url: components.url!)
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        
        if let data = data,
            let response = response as? HTTPURLResponse,
            (200 ..< 300) ~= response.statusCode,
            error == nil {
            let responseObject = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any]
            completion(responseObject, nil)
        }
        else {
            completion(nil, error)
            return
        }
    }
    task.resume()
}

sendRequest("myUrl", parameters: ["token":"..."]) { (responseObject, error) -> Void in
    
    if let responseObject = responseObject, error == nil {
        companyCountry = responseObject["country"] as! String
    }
    else {
        print(error ?? "Details Not Available")
        return
    }
}

print(companyCountry)

正如您可能假设的那样,在我的函数“sendRequest”被调用(操场)之后,我的变量“companyCountry”仍然为零,在这种情况下它应该是“US”。我的错误是什么?非常感谢您的帮助!!!

【问题讨论】:

  • 在返回响应之前,您仍在打印 companyCountry,请将打印内容移到 if let 中以验证您是否获得了一些数据
  • 在方法中打印值可以正常工作。我确实得到了正确的服务器响应。解析 JSON 数据也可以。但是我怎样才能访问异步函数之外的响应值呢?打印只是一个例子......
  • 这取决于你真正想做什么......
  • 感谢您的回答!我试图在调用异步函数 sendRequest() 时将网络请求后获得的值分配给全局变量: ... companyCountry = responseObject["country"] as!字符串 ...
  • 请阅读programmingios.net/what-asynchronous-means 以及该系列的下两篇文章。

标签: json swift api asynchronous completion


【解决方案1】:

成功的网络请求可能需要很长时间。通常它不到一秒,但最长可达 60 秒是可能的。即使只是一毫秒,您在调用网络请求的回调函数之前的很长一段时间内都会打印 companyCountry。

如果您想打印 companyCountry 以进行调试,请在回调中打印它。如果您想保留它,请将其存储到回调中的永久位置。

【讨论】:

    猜你喜欢
    • 2016-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多