ios - 处理失去连接的情况

标签 ios swift nsurlconnection nsurl

我使用 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/

相关文章:

ios - 将 MapKit 区域上传到 firebase

Swift 函数参数

ios - 表格 View 单元格大小更改

ios - 如何检查 AVPlayer 中的音频 channel 数?

iphone - 如何验证下载文件的完整性?

ios - 如何将委托(delegate)与 NSURLSession 一起使用

iphone - NSURLConnection 在服务器上发送数据两次

ios - 无法在 popViewControllerAnimated 上展开 Optional

ios - 静态库抛出链接器错误 : "No such file or directory"

ios - 使用 CATransform3DMakeRotation 截取具有 subview 的 UIView