迅速.网址返回nil

Ben*_*906 9 url fatal-error uiapplication swift

我试图在我的应用程序中打开一个网站,但由于某种原因,一行继续返回nil,继承我的代码:

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

let url = URL...是继续返回此错误的第一行():

致命错误:在展开Optional值时意外发现nil.

我该怎么做才能解决这个问题?

小智 16

我认为这会有所帮助.您的element.name可能包含单词之间的空格,因此addPercentEncoding会生成PercentEncoding字符串.

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)
}
Run Code Online (Sandbox Code Playgroud)


Bla*_*dow 13

此修复程序的 Swift 4 版本:

str.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
Run Code Online (Sandbox Code Playgroud)


小智 12

这绝对适合你。出现此问题的原因是字符串 URL 之间存在空格。要解决此问题,请使用

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
Run Code Online (Sandbox Code Playgroud)


use*_*890 7

不要用 (!) 强行打开它。当您使用 (!) 并且变量的值为 nil 时,您的程序会崩溃并出现该错误。相反,您希望使用“guard let”或“if let”语句安全地解开可选项。

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")
}
Run Code Online (Sandbox Code Playgroud)

如果这不起作用,则可能是 element.Name 有问题。因此,如果您仍然遇到问题,我会检查下这是否是可选的。

更新

我添加了一种可能的方法来检查 element.Name 属性,以查看您是否可以将其转换为 String 并创建您想要创建的所需 url。您可以在我之前发布的代码上方看到代码。