Проблема с преобразованием строки URL-адреса Википедии в URL-адрес в Swift - PullRequest
0 голосов
/ 04 августа 2020

Создаваемый мной URL-адрес действителен и вернет желаемый JSON при тестировании на Chrome, но не работает в моем проекте.

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 & executetext & generator = search & gsrsearch = intitle: Malibu% 20Beach & gsrlimit = 1 & redirects = 1 , но это также приведет к тому, что URL-адрес не будет возвращен, поскольку эта строка не может быть добавлена ​​в URL-адрес. Есть предложения о том, как преобразовать строку в URL-адрес?

1 Ответ

1 голос
/ 04 августа 2020

Проблема связана с символом | в 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)
}
...