在 Swift 中将 Wikipedia url 字符串转换为 URL 的问题

Posted

技术标签:

【中文标题】在 Swift 中将 Wikipedia url 字符串转换为 URL 的问题【英文标题】:Issue with turning Wikipedia url string into URL in Swift 【发布时间】: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 的任何建议?

【问题讨论】:

【参考方案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)

【讨论】:

遇到了同样的问题。谢谢!

以上是关于在 Swift 中将 Wikipedia url 字符串转换为 URL 的问题的主要内容,如果未能解决你的问题,请参考以下文章