Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/99.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 如何在openURL swift中捕获错误的URL_Ios_Swift2 - Fatal编程技术网

Ios 如何在openURL swift中捕获错误的URL

Ios 如何在openURL swift中捕获错误的URL,ios,swift2,Ios,Swift2,如果我的url末尾有一个空格,它将与EXC_BAD_指令崩溃 我原以为canOpenURL会被错误的URL所捕获,但事实并非如此 if let strurl = cell.url{ if (UIApplication.sharedApplication().canOpenURL(NSURL(string:strurl)!)) { UIApplication.sharedApplication().openURL(NSURL(string:strurl)!); }

如果我的url末尾有一个空格,它将与EXC_BAD_指令崩溃

我原以为canOpenURL会被错误的URL所捕获,但事实并非如此

if let strurl = cell.url{
    if (UIApplication.sharedApplication().canOpenURL(NSURL(string:strurl)!)) {
        UIApplication.sharedApplication().openURL(NSURL(string:strurl)!);
    }
}

在我的例子中,一个在末尾有额外空间的URL会使它崩溃。我可以修剪空白,但是其他的呢?是否有适当的方法捕获此错误?

您正在强制展开
NSURL
,如果恰好是
nil
,则会导致应用程序崩溃。要检查URL的有效性,还应在URL本身上使用
if let

if let strurl = cell.url,
   let url = NSURL(string: strurl) {
      if (UIApplication.sharedApplication().canOpenURL(url) {
          UIApplication.sharedApplication().openURL(url)
      }
}