迅速。网址返回nil

时间:2016-11-01 20:47:34

标签: swift url fatal-error uiapplication

我正在尝试在我的应用中打开一个网站,但由于某种原因,一行继续返回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)
    }
}

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

  

致命错误:在解包可选值时意外发现nil。

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

7 个答案:

答案 0 :(得分:9)

  

我认为这会有所帮助。    您的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)
}

答案 1 :(得分:3)

不要用(!)强行打开它。当你使用(!)并且变量的值为nil时,程序崩溃并且你得到了那个错误。相反,你想安全地用#34; guard 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")
}

如果没有这个诀窍,你可能会遇到element.Name的问题。因此,如果您仍然遇到问题,我会检查这是否可选。

<强>更新

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

答案 2 :(得分:1)

此修复程序的Swift 4版本:

str.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)

答案 3 :(得分:1)

这绝对适合您。由于您的字符串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

答案 4 :(得分:0)

这可能是一个编码问题。 你试过吗

let str = "http://en.wikipedia.org/wiki/\(element.Name)"
let encodedStr = str.stringByAddingPercentEncodingWithAllowedCharacters(NSCha‌​racterSet.URLQueryAl‌​lowedCharacterSet()

答案 5 :(得分:0)

它可能包含零宽度空间,顾名思义,它是Unicode字符,肉眼看不见

let data1 = [];
let data2 = [];
let data3 = [];
document.addEventListener("DOMContentLoaded", function(){
  if (document.getElementById('minus').checked) {
    let data1 = [-64, 31, 23, 34, 23, 30, 50, 43, 29, 64, 22, 34];
    let data2 = [-23, 45, 83, 74, 99, 83, 64, 72, 50, 44, 36, 45];
    let data3 = [-64, 75, 43, 24, 63, 72, 88, 24, 84, 93, 45, 60];
  } else {
    let data1 = [64, 31, 23, 34, 23, 30, 50, 43, 29, 64, 22, 34];
    let data2 = [23, 45, 83, 74, 99, 83, 64, 72, 50, 44, 36, 45];
    let data3 = [64, 75, 43, 24, 63, 72, 88, 24, 84, 93, 45, 60];
  }
});

//Further code that uses the variables we just set

答案 6 :(得分:0)

我猜您的网址在添加 element.Name 后格式不正确。 所以只需使用该功能

addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)

令人惊讶的是,URL 构造函数没有考虑 URL 格式