Search code examples
swift3nsurl

URL is not accepting query string with or (|) parameter swift 3


I am trying to implement nearbysearch Google web service with multiple types like in query type=department_store|grocery_or_supermarket

So, I have prepared a query string as mentioned below which is working fine at browser

let query = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=28.965198333333333,77.98569833333333&radius=3218&type=department_store|grocery_or_supermarket&key=API_KEY"

When I am trying to convert it to URL as mentioned below then it gives me error "URL invalid" because URL is not accepting query string with or (|) parameter

guard let url = URL(string: query) else { return completion(.Failure("URL invalid")) }

While it is working fine with a single type type=department_store

let query = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=28.965198333333333,77.98569833333333&radius=3218&type=grocery_or_supermarket&key=API_KEY"

Please suggest, how can I use multiple types with nearbysearch web service.

Thanks in advance.


Solution

  • Add percent encoding:

    guard let escapedQuery = query.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed),
          let url = URL(string: escapedQuery) else { return completion(.Failure("URL invalid")) }