Swift. URL returning nil

Benja0906 picture Benja0906 · Nov 1, 2016 · Viewed 22.3k times · Source

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?

Answer

Dipal Patel picture Dipal Patel · Mar 16, 2017

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)
}