简体   繁体   English

URL(string :)给出nil错误,即使在Swift中String不是nil

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

I have the following code: 我有以下代码:

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

This code is inside a Button and the Xcode console prints the codeString correctly, it's not nil and so it should open the URL of the codeString , instead, Xcode throws this error: 这段代码在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

The same thing happens in case of a Phone number or SMS string (I get the codeString value from a scanned QR code): 如果是电话号码或SMS字符串, codeString发生相同的事情(我从扫描的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

In case of a URL, like https//example.com, the app doesn't crash, no nil error, same for text, etc. So I really don't understand why I get that error even if the codeString is not nil . 如果是URL,例如https://example.com,则应用程序不会崩溃,没有nil错误,文本相同等。因此,即使codeString不为nil ,我也真的不明白为什么会收到该错误。

The string is not nil but it does not represent a valid URL. 字符串不是nil但是它不代表有效的URL。 You have to encode the URL. 您必须对URL进行编码。

However it's recommended to unwrap the optionals safely 但是,建议安全打开可选组件

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

The url is nil because it cannot be created without escaping spaces you got there. 该网址为nil因为如果不转义您到达的空格就无法创建该网址。

This would work: 这将工作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM