Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 563
Benja0906 Avatar asked Nov 01 '16 20:11

Benja0906


6 Answers

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)
}
like image 192
Dipal Patel Avatar answered Sep 22 '22 01:09

Dipal Patel


Swift 4 version for this fix:

str.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
like image 30
BlaShadow Avatar answered Sep 20 '22 01:09

BlaShadow


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
like image 37
Navdeep Paliwal Avatar answered Sep 20 '22 01:09

Navdeep Paliwal


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.

like image 34
user3353890 Avatar answered Sep 22 '22 01:09

user3353890


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

like image 28
JPilson Avatar answered Sep 23 '22 01:09

JPilson


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 
like image 24
Tema Tian Avatar answered Sep 22 '22 01:09

Tema Tian