Home > database >  Unable to set right language for google maps api
Unable to set right language for google maps api

Time:11-24

I have such function

func getCities(searchTerm: String) async throws -> [Prediction] {
        let string = "https://maps.googleapis.com/maps/api/place/autocomplete/json?input=\(searchTerm)&language=ru_RU&types=(cities)&key=KEY"
        guard let url = URL(string: string) else { throw NetworkError.badURL }
        let (data, response) = try await URLSession.shared.data(from: url)
        guard (response as? HTTPURLResponse)?.statusCode == 200 else {
            throw NetworkError.BadID
        }
        let result = try? JSONDecoder().decode(SearchCityModel.self, from: data)
        return result?.predictions ?? []
    }

When I try to use this url in browser with searchTerm in russian and english everything is ok. But when I try to set searchTerm in russian it is throw BadURL. If i use english or even type in russian but with english keyboard layout (Москва = Vjcrdf) I got needed results. How I can use russian and get results on the same language?

I have tried to change languages in URL but result the same

CodePudding user response:

In general it is mandatory to encode your request parameter. Especially if they are in a foreign language. You never know what signs they would contain. Some could breack your link.

Possible solution:

let parameter = text.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)

Don´t encode the whole url, just the parameter arguments.

  • Related