When you create your own NSError
object like that, that localizedDescription
is not generated for you. When URLSession
generates error objects, though, the localized description is populated:
let url = URL(string: "https://bad.domain")!
URLSession.shared.dataTask(with: url) { data, response, error in
if let error = error as? URLError {
print(error.localizedDescription) // “A server with the specified hostname could not be found.”
}
}.resume()
So, if you have an error and want to see the localized description, just do that. It simply will not work if you create your own NSError
object manually.
But generally, we wouldn't worry about the localized description and, instead, test for various code
values of URLError
, looking for a code
of .cannotFindHost
:
let url = URL(string: "https://bad.domain")!
URLSession.shared.dataTask(with: url) { data, response, error in
if let error = error as? URLError {
switch error.code {
case .cannotFindHost: print("cannotFindHost")
case .cancelled: print("cancelled")
case .badURL: print("badURL")
// ...
default: break
}
}
}.resume()
Or, alternatively, you can search for the old NSURLError
code values using NSError
, too, looking for NSURLErrorCannotFindHost
:
URLSession.shared.dataTask(with: url) { data, response, error in
if let error = error as NSError? {
switch error.code {
case NSURLErrorCannotFindHost: print("cannotFindHost")
case NSURLErrorCancelled: print("cancelled")
case NSURLErrorBadURL: print("badURL")
// ...
default: break
}
}
}.resume()
You can also “quick open” by pressing shift-command-O (the letter “Oh”), search for NSURLError
, uncheck the “Swift” button in the upper right corner of the quick open dialog:

When you open up the NSURLError.h
file, you can then see all the codes listed there.
But, no, just by creating a NSError
with the specified domain and code, the localizedDescription
isn't magically populated for you. URLSession
creates the proper error objects with descriptions, though.