NSURL致命错误

时间:2015-11-02 20:13:33

标签: swift nsurl

我插入网址后尝试在Swift中建立waze链接,我发现致命错误。

我的代码

let newName:String = closest.name.stringByReplacingOccurrencesOfString(" ", withString: "&", options: NSStringCompareOptions.LiteralSearch, range: nil)
    print(closest.name)
    print(newName)
    let url:String = "waze://?q=\(newName)"

    print(url)

    let navAdd: NSURL? = NSURL(string:url)// here is the error
    let wazeApp: NSURL? = NSURL(string: "http://itunes.apple.com/us/app/id323229106")!
    print(navAdd)
    if(true){
        UIApplication.sharedApplication().openURL(navAdd!)
    }else{
        UIApplication.sharedApplication().openURL(wazeApp!)
    }

,错误是:

  

致命错误:在解包可选值时意外发现nil

1 个答案:

答案 0 :(得分:0)

您已打开一个可选项,但不检查它是否为零。

if let navAdd = NSURL(string:url) {
    UIApplication.sharedApplication().openURL(navAdd)   
} else if let wazeApp = NSURL(string:"http://itunes.apple.com/us/app/id323229106"){
    UIApplication.sharedApplication().openURL(wazeApp)
} else {print("Url not found")}