处理丢失的连接

时间:2016-04-21 10:02:00

标签: ios swift nsurlconnection nsurl

我使用Swift以这种方式从Internet下载数据:

let postEndpoint: String = "http://webisitetest.com"
        guard let url = NSURL(string: postEndpoint) else {
            print("Error: cannot create URL")
            return
        }
        let urlRequest = NSURLRequest(URL: url)

        let config = NSURLSessionConfiguration.defaultSessionConfiguration()
        let session = NSURLSession(configuration: config)

        let task = session.dataTaskWithRequest(urlRequest, completionHandler: { (data: NSData?, response: NSURLResponse?, error: NSError?) in
            // this is where the completion handler code goes
            print(response)
            print(error)
        })

        task.resume()

因为我下载的图像和下载可以在几秒钟内(取决于连接),如果在下载期间用户失去连接,我该如何处理这种情况?

我想向他显示一条消息,例如“连接丢失,下载已取消,再试一次”,但我如何抓住此事件?

2 个答案:

答案 0 :(得分:0)

检查完成处理程序中是否存在error

let task = session.dataTaskWithRequest(urlRequest, completionHandler: { (maybeData: NSData?, maybeResponse: NSURLResponse?, maybeError: NSError?) in
    // check for error
    guard maybeError = nil else {
        print(maybeError!)
    }

    // otherwise process the request
    print(maybeResponse)
})

答案 1 :(得分:0)

任何故障都可以在完成块中处理。您还可以在配置中指定请求和资源超时前的秒数。

- (NSURLSessionConfiguration*) requestConfigurations
{
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration];

configuration.timeoutIntervalForRequest = 120;
configuration.timeoutIntervalForResource = 980.0;

return configuration;
}

错误中的错误代码可以帮助您区分失败类型。