Search code examples
iosnsurlsession

How to catch App Transport Security errors?


When using NSURLSession, if the URL does not conform to ATS, the dataTask is terminated. Is there a delegate method or anything that i can use to be notified of this error?


Solution

  • You can use data in error returned in dataTask completionHandler like this:

    let datatask = URLSession.shared.dataTask(with: URL(string: "http://example.com")!) {
    
            (data, response, error) in
    
            if let error = error {
    
                let isATSError = (error as NSError)._code == -1022
    
                if(isATSError) {
    
                    // it is an ATS error. do something!
                }
            }
    
            // no errors, continue
    
        }
        datatask.resume()