URL(string:) 即使字符串在 Swift 中不为 nil 也会给出 nil 错误

URL(string:) gives nil error even if the String is not nil in Swift

我有以下代码:

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

此代码在按钮内,Xcode 控制台正确打印 codeString,它不是 nil,因此它应该打开 URL 的 codeString,相反,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

如果是 Phone 号码或短信字符串(我从扫描的 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 错误,文本也一样,等等。所以我真的不明白为什么即使 codeString 不是 nil.

,我也会收到该错误

该字符串不是 nil,但它不代表有效的 URL。您必须对 URL.

进行编码

然而,建议安全地解开选项

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

url 是 nil 因为如果不转义您到达那里的空格就无法创建它。

这可行:

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