Swift创建NSURL时出错

问题描述:

这是我的代码。错误:fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)我不知道在哪里; S问题Swift创建NSURL时出错

res = "https://www.example.com/range.php?arr1=48.15&arr2=48.15&API_KEY=>code" 
    let url = NSURL(string: res)! // error line 
    print("url craeted" + res) 
    return url 
+5

'>'不是URL的有效字符。编码您的URL:http://*.com/q/24551816/2227743,http://*.com/a/30149081/2227743等 – Moritz

组合=>导致的指令失败,让我们的字符串不解释为一个字符串。 顺便说一句,我假设res已经在你的代码的其他地方被定义了,你想在以后的版本中将“url created”改成“url created”。

您可以使用扩展编码您的网址

extension String { 
    func urlEncodedString() -> String { 
     let urlEncodedString = self.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) 
     return urlEncodedString ?? self 
    } 
}