Swift:网络请求后的完成处理程序
Swift: completion handler after network request
我知道,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”。我的错误是什么?非常感谢您的帮助!!!
成功的网络请求可能需要很长时间。通常不到一秒,但也有可能长达 60 秒。即使只是一毫秒,在网络请求的回调函数被调用之前,您正在打印 companyCountry。
如果您想打印 companyCountry 用于调试目的,请在回调中打印它。如果您想保留它,请将其存储到回调中的永久位置。
我知道,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”。我的错误是什么?非常感谢您的帮助!!!
成功的网络请求可能需要很长时间。通常不到一秒,但也有可能长达 60 秒。即使只是一毫秒,在网络请求的回调函数被调用之前,您正在打印 companyCountry。
如果您想打印 companyCountry 用于调试目的,请在回调中打印它。如果您想保留它,请将其存储到回调中的永久位置。