简体   繁体   中英

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.

I thought canOpenURL would trap for a bad URL but it doesn't.

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. 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 . To check the validity of the URL you should be using if let on the URL itself as well.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM