【问题标题】:Handle losing connection处理失去连接
【发布时间】:2016-04-21 10:01:59
【问题描述】:

我使用 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()

因为我还下载图像并且可以在不同的秒数(取决于连接)下载,如果在下载过程中用户失去连接,我该如何处理这种情况?

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

【问题讨论】:

    标签: ios swift nsurlconnection nsurl


    【解决方案1】:

    检查您的完成处理程序中是否存在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)
    })
    

    【讨论】:

    • 当您说“检查错误”时,您的意思是这类问题存在特定类型的错误?
    • 是的,任何错误都将在完成处理程序中表示为一个对象。
    【解决方案2】:

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

    - (NSURLSessionConfiguration*) requestConfigurations
    {
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration];
    
    configuration.timeoutIntervalForRequest = 120;
    configuration.timeoutIntervalForResource = 980.0;
    
    return configuration;
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-20
      • 2013-05-07
      • 2023-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-05
      • 2014-02-28
      相关资源
      最近更新 更多