Swift. URL返回空

3b6akqbq  于 2022-10-31  发布在  Swift
关注(0)|答案(8)|浏览(225)

我试图在我的应用程序中打开一个网站,但由于某种原因,一行不断返回零,以下是我的代码:

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...)不断返回此错误:
致命错误:在展开可选值时意外地找到nil。
我该怎么做才能解决这个问题?

blmhpbnm

blmhpbnm1#

我想这会有帮助。您的element.name可能在单词之间包含空格,因此addingPercentEncoding将成为PercentEncoding字符串。

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)
}
am46iovg

am46iovg2#

此修复的Swift 4版本:

str.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
kuhbmx9i

kuhbmx9i3#

这对你来说绝对有效。这个问题是由于你的字符串URL之间的空格造成的。要解决这个问题,请使用

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
tzcvj98z

tzcvj98z4#

不要用(!)强制打开它。当你使用(!)并且变量的值为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属性,看看是否可以将其转换为String,并创建想要创建的url。您可以在我之前发布的代码上面看到代码。

goqiplq2

goqiplq25#

我猜在添加element.Name后,您的URL格式不正确,因此只需使用函数

addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)

令人惊讶的是,URL构造函数没有考虑URL格式

xytpbqjk

xytpbqjk6#

它可能包含零宽度空格,顾名思义,它是一个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
wfauudbj

wfauudbj7#

这可能是一个编码问题。你试过吗

let str = "http://en.wikipedia.org/wiki/\(element.Name)"
let encodedStr = str.stringByAddingPercentEncodingWithAllowedCharacters(NSCha‌​racterSet.URLQueryAl‌​lowedCharacterSet()
rxztt3cl

rxztt3cl8#

URLComponents是为了避免URL组件的手动转义(适用于每个不同的规则)

public func configure()
{
    if var urc = URLComponents(string: "https://fake/") {
        urc.host = your real hostname with whatever characters are not allowed in hostname
        ... same deal for other url components
        YourScope.baseUrlPath = urc.url?.absoluteString
    }
}

相关问题