2016-04-21 70 views
0

我在網上以這種方式使用雨燕下載數據:手柄失去連接

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() 

因爲我還可以下載圖片和下載可在各種秒內(取決於連接),如果下載過程中用戶斷開連接,我怎麼處理這種情況?

我想向他展示一條消息,例如「連接丟失,下載取消,再試一次」,但我怎麼捕獲這個事件?

回答

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) 
}) 
+0

當你說「檢查錯誤」你的意思是這種類型的問題有一個特定類型的錯誤? – gianni

+0

是的,任何錯誤都將在完成處理程序中表示爲對象。 – Eimantas

0

任何故障可以在完成塊來處理。您還可以指定配置中的請求和資源超時前的秒數。

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

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

return configuration; 
} 

來自錯誤的錯誤代碼可以幫助您區分故障類型。