[英]How do I trap a bad URL in openURL swift
If my url has a space at the end it crashes with EXC_BAD_INSTRUCTION. 如果我的网址末尾有空格,则会崩溃并显示EXC_BAD_INSTRUCTION。
I thought canOpenURL would trap for a bad URL but it doesn't. 我以为canOpenURL会捕获错误的URL,但事实并非如此。
if let strurl = cell.url{
if (UIApplication.sharedApplication().canOpenURL(NSURL(string:strurl)!)) {
UIApplication.sharedApplication().openURL(NSURL(string:strurl)!);
}
}
In my case a URL with an extra space at the end crashes it. 就我而言,结尾处有多余空格的URL会将其崩溃。 I can trim white space, but what about anything else?
我可以修剪空白,但是还有什么呢? Is there a proper way to trap for this error?
有没有适当的方法来捕获此错误?
You are force unwrapping NSURL
which causes the app to crash if it happens to be nil
. 您强行解开
NSURL
,如果碰巧为nil
,则会导致应用程序崩溃。 To check the validity of the URL you should be using if let
on the URL itself as well. 要检查URL的有效性,您还应该在URL本身上使用
if let
。
if let strurl = cell.url,
let url = NSURL(string: strurl) {
if (UIApplication.sharedApplication().canOpenURL(url) {
UIApplication.sharedApplication().openURL(url)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.