Swift。 URL 返回零
Swift. URL returning nil
我正在尝试在我的应用程序中打开一个网站,但由于某种原因,一行一直返回 nil,这是我的代码:
let url = URL(string: "http://en.wikipedia.org/wiki/\(element.Name)")!
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(url)
}
}
第一行(let url = URL...
)不断返回此错误:
fatal error: unexpectedly found nil while unwrapping an Optional value.
我应该怎么做才能解决这个问题?
这可能是编码问题。
你试过了吗
let str = "http://en.wikipedia.org/wiki/\(element.Name)"
let encodedStr = str.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()
不要用 (!) 强制解包。当您使用 (!) 并且变量的值为 nil 时,您的程序会崩溃并出现该错误。相反,您想使用 "guard let" 或 "if let" 语句安全地解包可选。
guard let name = element.Name as? String else {
print("something went wrong, element.Name can not be cast to String")
return
}
if let url = URL(string: "http://en.wikipedia.org/wiki/\(name)") {
UIApplication.shared.openURL(url)
} else {
print("could not open url, it was nil")
}
如果还是不行,您可能遇到了 element.Name 的问题。因此,如果您仍然遇到问题,我会检查下一个是否是可选的。
更新
我添加了一种可能的方法来检查 element.Name 属性 以查看您是否可以将其转换为字符串并创建您想要创建的所需 url。您可以在我之前发布的代码上方看到代码。
I think this will help.
Your element.name may contain space between words so addingPercentEncoding make PercentEncoding string.
let txtAppend = (element.Name).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
let url = "http://en.wikipedia.org/wiki/\(txtAppend!)"
let openUrl = NSURL(string: url)
if #available(iOS 10.0, *) {
UIApplication.shared.open(openUrl as! URL, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(openUrl as! URL)
}
Swift 此修复的 4 版本:
str.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
这绝对适合你。问题是由于字符串 URL 之间的 space 而发生的。要解决此问题,请使用
let imagePath = "https://homepages.cae.wisc.edu/~ece533/images/arcti cha re.png"
let urlString = imagePath.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) //This will fill the spaces with the %20
let url = URL(string: urlString) //This will never return nil
可能包含Zero-width-space,顾名思义,是Unicode字符,肉眼不可见
extension String {
func replacePattern(pattern: String, replaceWith: String = "") -> String {
do {
let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options.caseInsensitive)
let range = NSMakeRange(0, self.count)
return regex.stringByReplacingMatches(in: self, options: [], range: range, withTemplate: replaceWith)
} catch {
return self
}
}
var fixZeroWidthSpace: String {
addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)?.replacePattern(pattern: "%E2%80%8B", replaceWith: "") ?? ""
}
}
let url = urlString.fixZeroWidthSpace
我猜你的 URL 在添加 element.Name
后格式不正确。
所以只需使用函数
addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
令人惊讶的是 URL 构造函数没有考虑 URL 格式
我正在尝试在我的应用程序中打开一个网站,但由于某种原因,一行一直返回 nil,这是我的代码:
let url = URL(string: "http://en.wikipedia.org/wiki/\(element.Name)")!
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(url)
}
}
第一行(let url = URL...
)不断返回此错误:
fatal error: unexpectedly found nil while unwrapping an Optional value.
我应该怎么做才能解决这个问题?
这可能是编码问题。 你试过了吗
let str = "http://en.wikipedia.org/wiki/\(element.Name)"
let encodedStr = str.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()
不要用 (!) 强制解包。当您使用 (!) 并且变量的值为 nil 时,您的程序会崩溃并出现该错误。相反,您想使用 "guard let" 或 "if let" 语句安全地解包可选。
guard let name = element.Name as? String else {
print("something went wrong, element.Name can not be cast to String")
return
}
if let url = URL(string: "http://en.wikipedia.org/wiki/\(name)") {
UIApplication.shared.openURL(url)
} else {
print("could not open url, it was nil")
}
如果还是不行,您可能遇到了 element.Name 的问题。因此,如果您仍然遇到问题,我会检查下一个是否是可选的。
更新
我添加了一种可能的方法来检查 element.Name 属性 以查看您是否可以将其转换为字符串并创建您想要创建的所需 url。您可以在我之前发布的代码上方看到代码。
I think this will help. Your element.name may contain space between words so addingPercentEncoding make PercentEncoding string.
let txtAppend = (element.Name).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
let url = "http://en.wikipedia.org/wiki/\(txtAppend!)"
let openUrl = NSURL(string: url)
if #available(iOS 10.0, *) {
UIApplication.shared.open(openUrl as! URL, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(openUrl as! URL)
}
Swift 此修复的 4 版本:
str.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
这绝对适合你。问题是由于字符串 URL 之间的 space 而发生的。要解决此问题,请使用
let imagePath = "https://homepages.cae.wisc.edu/~ece533/images/arcti cha re.png"
let urlString = imagePath.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) //This will fill the spaces with the %20
let url = URL(string: urlString) //This will never return nil
可能包含Zero-width-space,顾名思义,是Unicode字符,肉眼不可见
extension String {
func replacePattern(pattern: String, replaceWith: String = "") -> String {
do {
let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options.caseInsensitive)
let range = NSMakeRange(0, self.count)
return regex.stringByReplacingMatches(in: self, options: [], range: range, withTemplate: replaceWith)
} catch {
return self
}
}
var fixZeroWidthSpace: String {
addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)?.replacePattern(pattern: "%E2%80%8B", replaceWith: "") ?? ""
}
}
let url = urlString.fixZeroWidthSpace
我猜你的 URL 在添加 element.Name
后格式不正确。
所以只需使用函数
addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
令人惊讶的是 URL 构造函数没有考虑 URL 格式