我是 Swift 的新手,正在编写一个从扫描仪读取数据然后将其发布到网页的应用程序。我现在从主 Storyboard上的文本编辑字段中获取数据,当我按下查找按钮触发以下代码时,它会抛出以下异常。我设置了一个断点并在 temp 在 URL 中使用它之前检查了它的值,并且它的颜色正确(不是零)。如果我在编辑字段中输入,那么代码从那时起就可以正常工作;即使我使用清除图标 (x) 删除了编辑字段的内容,也会打开页面。
我不知道哪个变量是 nil 以及如何更正或保护代码。任何帮助将不胜感激。
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
func setStatus(_ status: String)
{
statusLabel.text = status
}
func processRead(_ data: String?)
{
if (data != nil)
{
var temp: String = data!
setStatus(temp)
temp = "foo.com?data=" + temp
let url: URL = URL(string: temp)! // <<<< THROWS EXCEPTION / BREAK POINT
UIApplication.shared.openURL(url)
}
}
更新 -- 更正的代码 --
func setStatus(_ status: String)
{
statusLabel.text = status
}
func processRead(_ data: String?)
{
if (data != nil && !data!.isEmpty)
{
let temp = "https://foo.com/data=" + data!.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!);
if let url = URL(string: temp)
{
setStatus(data!)
UIApplication.shared.openURL(url)
}
else
{
print("Bad URL: " + temp);
}
}
}
最佳答案
temp
可能包含一些在 URL 的查询部分中无效的字符。这使得整个字符串不是有效的 URL,因此 URL.init
返回 nil。您需要通过调用 addingPercentEncoding
来转义这些字符:
URL(string: "foo.com?data=" + temp.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!)
关于URL 上的 Swift Nil 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50587780/