【问题标题】:Issue with turning Wikipedia url string into URL in Swift在 Swift 中将 Wikipedia url 字符串转换为 URL 的问题
【发布时间】:2020-08-04 19:39:07
【问题描述】:

我创建的 URL 有效,在 Chrome 上测试时会返回所需的 JSON,但在我的项目中失败。

func createWikipediaURL(place: String) -> URL? {
    let _place = place.replacingOccurrences(of: " ", with: "%20")
    let urlStr =
    "https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts|pageimages&exintro&explaintext&generator=search&gsrsearch=intitle:\(_place)&gsrlimit=1&redirects=1"

    if let url = URL(string:urlStr) {
        return url
    } else {
        return nil
    }
}

使用参数“Malibu Beach”,该函数将创建正确的 URL,https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts|pageimages&exintro&explaintext&generator=search&gsrsearch=intitle:Malibu%20Beach&gsrlimit=1&redirects=1,但也将导致不返回任何 URL,因为该字符串无法转换为 URL。关于如何将字符串变成 URL 的任何建议?

【问题讨论】:

    标签: swift url wikipedia


    【解决方案1】:

    问题在于urlStr 中的| 字符。我建议使用 Strings addingPercentEncoding 方法来使字符串 url 安全。这样做意味着您也不需要手动替换 place 的空格。

    func createWikipediaURL(place: String) -> URL? {
        let urlStr = "https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts|pageimages&exintro&explaintext&generator=search&gsrsearch=intitle:\(place)&gsrlimit=1&redirects=1"
    
        // Replaces special characters with their percent encoded counter-parts.
        guard let escapedUrlStr = urlStr.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else { return nil }
    
        // There's no need for an if statement; URL can be returned as-is.
        return URL(string:escapedUrlStr)
    }
    

    【讨论】:

    • 遇到了同样的问题。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-16
    • 2018-03-08
    • 2018-06-08
    • 1970-01-01
    • 2020-10-12
    • 2013-08-29
    • 1970-01-01
    相关资源
    最近更新 更多