URLError Safe to Use In URLSession response?

Hello,


Foundation declares a URLError struct with a comment saying that URLError describes errors in the URL error domain:


/// Describes errors in the URL error domain.
public struct URLError {
     /// The type of an error code.
    @objc public enum Code : Int {
        case unknown
        case ...
     }
}


In the response of URLSession.dataTask(with url: URL, completionHandler: (Data?, URLResponse?, Error?) ),

casting the Error to a URLError succeeds.


Does URLSession now always return a URLError if an error occurred, or is it only in some cases?

If so, are there plans to update the signatures of the URLSession.dataTask methods to the URLError type?



Thanks!

Replies

Does URLSession now always return a URLError if an error occurred, or is it only in some cases?

No. While I’ve never seen anything other than an

NSURLErrorDomain
come back from NSURLSession, the API does not guarantee that. If you want to treat the error as a
URLError
, you must conditionally cast it and do something reasonable if the cast fails.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"