iosswifturltimeout

How to get timeout info from dataTask


I have the following code for requesting data from an external 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()

The timeoutInterval is set to 10.0. But how can I get back info on if the request/session timed out, or how long the request/session took the complete? I will then use that info to determine which function I should call.

Any help is much appreciated!


Solution

  • If the error is not nil then cast error as URLError and check the code is .timeout or not. Here is the code.

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