【问题标题】:URL(string:) gives nil error even if the String is not nil in Swift即使字符串在 Swift 中不是 nil,URL(string:) 也会给出 nil 错误
【发布时间】:2019-07-08 09:35:05
【问题描述】:

我有以下代码:

print("CODE STRING SELECTED: \(codeString)")
let aURL = URL(string: codeString)!
if UIApplication.shared.canOpenURL(aURL) { UIApplication.shared.openURL(aURL) }

此代码在 Button 内,Xcode 控制台正确打印 codeString,它不是 nil,因此它应该打开 codeString 的 URL,相反,Xcode 会抛出此错误:

CODE STRING SELECTED: mailto:john@doe.com?subject=Subject here&body=Lorem ipsum dolor sit, amet quatum.

Fatal error: Unexpectedly found nil while unwrapping an Optional value
2019-07-08 11:19:56.076467+0200 QRcode[2751:1043394] Fatal error: Unexpectedly found nil while unwrapping an Optional value

如果是电话号码或 SMS 字符串,也会发生同样的事情(我从扫描的 QR 码中获得 codeString 值):

CODE STRING SELECTED: tel:+1 2345678901
Fatal error: Unexpectedly found nil while unwrapping an Optional value

CODE STRING SELECTED: SMSTO:+1012345678:lorem ipsum dolor sit, amet
Fatal error: Unexpectedly found nil while unwrapping an Optional value

如果是 URL,例如 https//example.com,应用程序不会崩溃,没有 nil 错误,文本相同等。所以我真的不明白为什么我会收到这个错误,即使 @ 987654328@ 不是nil

【问题讨论】:

  • 你有没有考虑过在你访问它时做一个保护让来确认它不是 nil ?

标签: ios swift string null qr-code


【解决方案1】:

字符串不是nil,但它不代表有效的 URL。您必须对 URL 进行编码。

但是建议安全地解开选项

if let encodedString = codeString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
   let aURL = URL(string: encodedString), UIApplication.shared.canOpenURL(aURL) { 
    UIApplication.shared.openURL(aURL) 
}

【讨论】:

  • 你说得对,@vadian,非常感谢你的帮助,我会接受你的回答
  • 绝妙的解决方案!
【解决方案2】:

网址是nil,因为如果没有转义空格,就无法创建它。

这可行:

guard let escapedString = codeString.addingPercentEncoding(withAllowedCharacters: urlQuoeryAllowed), 
      let url = URL(string: escapedString) else {
 return
}

【讨论】:

    猜你喜欢
    • 2013-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-28
    • 1970-01-01
    • 2016-12-12
    • 1970-01-01
    • 2015-04-02
    相关资源
    最近更新 更多