2015-07-13 59 views
5

在我目前正在構建的iOS應用程序中,我試圖在會話超時時向用戶顯示消息。我閱讀了NSURLSessionDelegate的文檔,但找不到任何讓我知道會話是否超時的方法。我如何去做這件事?任何幫助表示讚賞。iOS Swift:如何查找NSURLSession是否超時

+0

我不是確定它是否適用於'NSURLSession',但是'NSURLConnection'將會失敗,委託方法將被調用,錯誤代碼爲'NSURLErrorTimeOut',如本答案所述:http://stackoverflow.com/a/12819297/433373 (編輯:關於'-sendSynchronousRequest:returningResponse:error:'的答案ID,但是 '-connection:didFailWithError:'也返回一個'NSError'對象。您可以檢查) –

回答

8

可以調用的方法是這樣的:

let request = NSURLRequest(URL: NSURL(string: "https://evgenii.com/")!) 
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) in 

     if error != nil { 

      if error?.code == NSURLErrorTimedOut { 
       println("Time Out") 
       //Call your method here. 
      } 
     } else { 

      println("NO ERROR") 
     } 

    } 
    task.resume() 
+0

看起來不太健壯(或未來的證明)。您正在對錯誤描述進行硬編碼;它可能會在未來的操作系統更新中更改(而不是用戶可能會將其設備設置爲除英語之外的其他語言)。您可以使用 –

+0

:print(error「ErrorDefault」) – johnny

0

我使用以下斯威夫特extension檢查錯誤是否是超時或其它網絡錯誤,用斯威夫特4

extension Error { 

    var isConnectivityError: Bool { 
     // let code = self._code || Can safely bridged to NSError, avoid using _ members 
     let code = (self as NSError).code 

     if (code == NSURLErrorTimedOut) { 
      return true // time-out 
     } 

     if (self._domain != NSURLErrorDomain) { 
      return false // Cannot be a NSURLConnection error 
     } 

     switch (code) { 
     case NSURLErrorNotConnectedToInternet, NSURLErrorNetworkConnectionLost, NSURLErrorCannotConnectToHost: 
      return true 
     default: 
      return false 
     } 
    } 

}