iOS Swift:如何查找NSURLSession是否已超时

Sph*_*Cow 9 ios nsurlsession swift

在我正在构建的iOS应用程序中,我试图在会话超时时向用户显示消息.我阅读了文档NSURLSessionDelegate但是没有找到任何方法让我知道会话是否超时.我该怎么做呢?任何帮助表示赞赏.

Dha*_*esh 14

你可以用这种方式调用方法:

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()
Run Code Online (Sandbox Code Playgroud)


Aam*_*irR 6

我正在使用以下 Swiftextension检查错误是否是超时或其他网络错误,使用 Swift 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
        }
    }

}
Run Code Online (Sandbox Code Playgroud)