Swift. URL returning nil

早过忘川 提交于 2020-06-13 19:03:27

问题


I am trying to open a website in my app, but for some reason one line keeps returning nil, heres my code:

let url = URL(string: "http://en.wikipedia.org/wiki/\(element.Name)")!
    if #available(iOS 10.0, *) {
        UIApplication.shared.open(url, options: [:], completionHandler: nil)
    } else {
        UIApplication.shared.openURL(url)
    }
}

It's the first line (let url = URL...) that keeps on returning this error:

fatal error: unexpectedly found nil while unwrapping an Optional value.

What should I do to fix this?


回答1:


Don't force unwrap it with (!). When you use (!) and the value of the variable is nil, your program crashes and you get that error. Instead, you want to safely unwrap the optional with either a "guard let" or an "if let" statement.

guard let name = element.Name as? String else {
    print("something went wrong, element.Name can not be cast to String")
    return
}

if let url = URL(string: "http://en.wikipedia.org/wiki/\(name)") {
    UIApplication.shared.openURL(url)
} else {
    print("could not open url, it was nil")
}

If that doesn't do the trick, you may have an issue with element.Name. So I would check to see if that's an optional next if you're still having issues.

Update

I added a possible way to check the element.Name property to see if you can cast it as a String and create the desired url you're looking to create. You can see the code above the code I previously posted.




回答2:


I think this will help. Your element.name may contain space between words so addingPercentEncoding make PercentEncoding string.

let txtAppend = (element.Name).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
let url = "http://en.wikipedia.org/wiki/\(txtAppend!)"
let openUrl = NSURL(string: url)
if #available(iOS 10.0, *) {
    UIApplication.shared.open(openUrl as! URL, options: [:], completionHandler: nil)
} else {
    UIApplication.shared.openURL(openUrl as! URL)
}



回答3:


Swift 4 version for this fix:

str.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)



回答4:


it may be an encoding issue. have you tried

let str = "http://en.wikipedia.org/wiki/\(element.Name)"
let encodedStr = str.stringByAddingPercentEncodingWithAllowedCharacters(NSCha‌​racterSet.URLQueryAl‌​lowedCharacterSet()


来源:https://stackoverflow.com/questions/40368389/swift-url-returning-nil

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!