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?
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)
}
Swift 4 version for this fix:
str.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
This will definitely works for you. The problem is occurring due to space in between your string URL. To fix this use
let imagePath = "https://homepages.cae.wisc.edu/~ece533/images/arcti cha re.png"
let urlString = imagePath.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) //This will fill the spaces with the %20
let url = URL(string: urlString) //This will never return nil
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.
I'm going to guess that your URL is not properly formated after adding the element.Name
.
so just use the function
addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
It's just surprising that the URL constructor doesn't take the URL format into consideration
It may contain Zero-width-space, as the name suggests, it is a Unicode character, invisible to the naked eye
extension String {
func replacePattern(pattern: String, replaceWith: String = "") -> String {
do {
let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options.caseInsensitive)
let range = NSMakeRange(0, self.count)
return regex.stringByReplacingMatches(in: self, options: [], range: range, withTemplate: replaceWith)
} catch {
return self
}
}
var fixZeroWidthSpace: String {
addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)?.replacePattern(pattern: "%E2%80%8B", replaceWith: "") ?? ""
}
}
let url = urlString.fixZeroWidthSpace
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With