0

I am trying to construct an URL with filter parameters, like so:

let url = URL(string: "http://myapi.com/api/customers?filter={\"where\":{\"name\":\"myName\"}}")

But this returns nil. Is there a way to have an URL object of this format? Or should I use another method to construct my request?

Thanks in advance !

M. Garrigues
  • 87
  • 10
  • 3
    Use URLComponents, see for example https://stackoverflow.com/a/24888789/1187415 or https://stackoverflow.com/a/43668198/1187415. – Martin R Sep 27 '18 at 12:40

2 Answers2

2
var url = URLComponents(string: "http://myapi.com/api/customer")!

url.queryItems = [
    URLQueryItem(name: "filter", value: "{\"where\":{\"name\":\"myName\"}}")
]
meggar
  • 1,219
  • 1
  • 10
  • 18
1

You have to add percent encoding to the string if it doesn't starts with http://:

let string = "myapi.com/api/customers?filter={\"where\":{\"name\":\"myName\"}}"

let escaped = string.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!

let url = URL(string: escaped)
ielyamani
  • 17,807
  • 10
  • 55
  • 90