当您像这样创建自己的NSError
对象时,它localizedDescription
不会为您生成。但是,当URLSession
生成错误对象时,会填充本地化描述:
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()
因此,如果您有错误并想查看本地化描述,请执行此操作。NSError
如果您手动创建自己的对象,它根本不起作用。
但一般来说,我们不会担心本地化描述,而是会测试 的各种code
值URLError
,寻找 的code
a .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()
或者,您也可以NSURLError
使用 搜索旧代码值NSError
,寻找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()
您也可以通过按shift- command- O(字母“哦”)“快速打开”,搜索NSURLError
,取消选中快速打开对话框右上角的“Swift”按钮:

打开NSURLError.h
文件时,您可以看到那里列出的所有代码。
NSError
但是,不,仅仅通过使用指定的域和代码创建一个,并localizedDescription
不会神奇地为您填充。URLSession
但是,创建带有描述的正确错误对象。