我有一个使用 Swift 3 的问题,我试图从我的完成闭包中访问任务变量,但它不可用。如果我尝试访问块内的“任务”,我得到“错误:使用未解析的标识符'任务'”我做错了什么?
typealias completionHandler = (data: Data?, httpResponse: HTTPURLResponse?, validServer: Bool, serverRealm: String?, serverVersion: String?) -> Void
typealias failureHandler = (data: Data?, response: URLResponse?, error: NSError?) -> Void
func ping(address: String, completionBlock: completionHandler, failureBlock: failureHandler?) -> URLSessionDataTask? {
guard var addressComponents = URLComponents(string: address) else {
let error = NSError(domain: "PING", code: 99, userInfo: [NSLocalizedDescriptionKey : "Invalid URL: \(address)"])
failureBlock?(data: nil, response: nil, error: error)
return nil
}
addressComponents.path = Paths.ping.rawValue
let request = URLRequest(url: addressComponents.url!, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: gsTimeout)
//--------------------------------------------------------------------------------
// Ping the server and process the repsonse
//--------------------------------------------------------------------------------
var task: URLSessionDataTask!
task = session.dataTask(with: request) { (data, response, error) in
print("Task: \(task)")
if error == nil {
if let response = response as? HTTPURLResponse {
let results = self.parseHeader(response)
print("Results: \(results)")
if results.isServer == true {
completionBlock(data: data, httpResponse: response, validServer: results.isServer, serverRealm: results.realm, serverVersion: results.serverVersion)
}
}
} else {
failureBlock?(data: data, response: response, error: error)
}
}
task.taskDescription = Paths.ping.rawValue
task.resume()
return task
}
现在更新了工作代码。如果您在块内使用它,任务是可用的。感谢大家