1

I have a URL that takes any String like this:

https://test@api.search?query=\(productSearchString)&limit=1

Now my problem is that this works with for example "iphone" but it crashes with "iphone 12". I tried encoding it like this:

guard let escapedResourceString = resourceString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) else { return  }

but this doesn't seem to work in my case because it is returning an incorrect URL that I can not use with my API.

How can I fix this, so the user can type in anything he want but the URL should be created and my API should be able to work with it.

If you need anything more just let me know.

Chris
  • 1,828
  • 6
  • 40
  • 108

1 Answers1

1

Your parameters needs to be url encoded.

You can use URLComponents to create your URL and pass your parameters as URLQueryItem instances, like that:

let productSearchString = "iphone 12"
var urlComponents = URLComponents(string: "https://test@api.search")
urlComponents?.queryItems = [
    URLQueryItem(name: "query", value: productSearchString),
    URLQueryItem(name: "limit", value: "1")
]
let url = urlComponents?.url

print(url?.absoluteString ?? "nil") // https://test@api.search?query=iphone%2012&limit=1
gcharita
  • 7,729
  • 3
  • 20
  • 37
  • i updated my question, in my case the `String` is not actually at the end but in the middle. Is your answer still working for this? And what exactly is your code doing? – Chris Feb 13 '21 at 11:38
  • `limit=1` was just an example, in reality there can be anything behind that, even more paramters depends on the situation in my case :D sorry if I didn't make that clear.. – Chris Feb 13 '21 at 11:46
  • is there not a simple way to `encode` my searchString and simply populate my actual `URL` with it? – Chris Feb 13 '21 at 11:47
  • @Chris `URLComponents` can be used to create a url from separate components, in your case from a string that is valid and some query parameters that needs to be url encoded. – gcharita Feb 13 '21 at 11:48
  • @Chris to compose the url yourself you need to run multiple times `addingPercentEncoding(withAllowedCharacters:)` function passing `.urlQueryAllowed` as allowed characters set for each parameter value. I think `URLComponents` is far easier. – gcharita Feb 13 '21 at 11:52
  • @Chris to pass more parameters modify the code to create more `URLQueryItem` instances and pass them in the `queryItems` property. – gcharita Feb 13 '21 at 11:54