Search code examples
swifturlfatal-erroruiapplication

Swift. URL returning nil


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?


Solution

  • 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.