-2

我有一个使用 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
}

现在更新了工作代码。如果您在块内使用它,任务是可用的。感谢大家

4

1 回答 1

1

您的代码没有任何问题。它编译得很好。

在调试器中暂停时,您无法获得使用 LLDBpo的价值,因为您在完成块内暂停。task您从未在此代码中捕获task(您没有引用它),因此它不在此处的范围内。只有在闭包内部实际引用的外部范围才会被闭包捕获。

于 2016-06-23T15:31:32.013 回答