如何在 NSURL 构造函数 returns nil 之后获取错误信息?

How to get an error info after NSURL constructor returns nil?

let url = NSURL(string: "http://example.com")

据我了解NSURLreturnsnil,当其构建失败时。

如何获取失败错误信息?

据我所知,URL 失败的主要原因是 URL 个字符无效。

您可以通过...来解决这个问题

let theURLString = // your url string

let validURLString = theURLString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLPathAllowedCharacterSet())

let url = NSURL(string: validURLString)

如果没有看到您实际尝试使用的字符串,很难判断问题出在哪里。

不幸的是,NSURL 不会告诉您为什么 URL 创建失败。

NSURL 上执行 ALT+CLICK 时的 Xcode 弹出窗口:

Handling Object Creation Failure
The NSURL class fails to create a new NSURL object if the path being passed is not well formed; the path must comply with RFC 2396. Examples of cases that will not succeed are strings containing space characters and high-bit characters. If creating an NSURL object fails, the creation methods return nil, which you must be prepared to handle.

所以 NSURL 如果失败,将只是 return nil,而不会提供任何进一步的细节。像往常一样使用 Optional 绑定、Optional 链接、保护或任何其他已知技术来安全地解包 optionals,并遵循 Fogmeister 的建议并在使用前对 URL 字符串进行编码。

更新答案 Swift 5

let theURLString = "URL" // your url string

let validURLString = theURLString.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)

let url = URL(string: validURLString)