我使用 Swift 以这种方式从互联网下载数据:
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()
因为我还下载图像,并且可以在不同的秒数内下载(取决于连接),如果在下载过程中用户失去连接,我该如何处理这种情况?
我想向他显示一条消息,例如“连接丢失,下载取消,重试”,但我如何捕获此事件?
最佳答案
检查完成处理程序中是否存在错误
:
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)
})
关于ios - 处理失去连接的情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36766204/