1

I have the following two base urls for my API methods:

let stagingHost = "myApi.test.com/sub1"

let productionHost = "myApi.test.com/sub2"

when I build the url for any API call in my app, I do the following:

var components = URLComponents()
components.scheme = "https"
components.host = stagingHost //or productionHost doesn't matter
components.path = "apiMethodPath"
let url = components.url

this will result in the following url:

https://myApi.test.com%2Fsub1/apiMethodPath which is an invalid URL for my api due to the automatically added %2F characters to the host component, how to prevent the host component from precent escaping its url string ?

p.s. I can't add /sub1 and /sub2 as a path component to a lot of api methods depending on the chosen environment (staging or production), because it's going to be a time consuming process.

JAHelia
  • 4,684
  • 14
  • 52
  • 102
  • Why not use simple string manipulation to build the URL? You can't put part of the path in the host component without it being interpreted as part of the host name – Paulw11 Apr 16 '20 at 13:29
  • I consider this a limitation in the `URLComponents` class not allowing for such cases – JAHelia Apr 16 '20 at 13:30
  • How is it a limitation? You are trying to put a path into the host component. That is just wrong. The class is doing exactly the right thing; percent encoding the character that isn't valid as part of a host name. All you need to do is `URL(string:"https://\(stagingHost)/\(apiMethodPath)")!` – Paulw11 Apr 16 '20 at 13:43

0 Answers0