如何从 dataTask 获取超时信息

How to get timeout info from dataTask

我有以下用于从外部请求数据的代码API:

var request = URLRequest(url: myURL!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)                 
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
    if error != nil {
        print(error)
    } else {
        let httpResponse = response as? HTTPURLResponse
    }
})

dataTask.resume()

timeoutInterval设置为10.0。但是,如果 request/session 超时,或者 request/session 完成了多长时间,我该如何取回有关 的信息?然后我将使用该信息来确定我应该调用哪个函数。

非常感谢任何帮助!

如果错误不是 nil,则将错误转换为 URLError 并检查 code 是否为 .timeout。这是代码。

var request = URLRequest(url: myURL!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)

request.httpMethod = "GET"
request.allHTTPHeaderFields = headers

let session = URLSession.shared

let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
    if (error != nil) {
        if let error = error as? URLError {
            if error.code == .timedOut {
                print("Timeout error")
            }
        }
        
        print(error)
    } else {
        let httpResponse = response as? HTTPURLResponse
    }
})

dataTask.resume()