swift – NSURL构造函数返回nil后如何获取错误信息?

前端之家收集整理的这篇文章主要介绍了swift – NSURL构造函数返回nil后如何获取错误信息?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
let url = NSURL(string: "http://example.com")

据我所知NSURL返回nil,当它的构造失败时.

如何获取失败错误信息?

解决方法

不幸的是,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将返回nil,而不提供任何进一步的细节.通常使用可选绑定,可选链接,防护或任何其他已知技术来安全地解包选项,并遵循Fogmeister的建议并在使用前对URL字符串进行编码.

猜你在找的Swift相关文章