URLComponents.url is nil

Fogmeister picture Fogmeister · Oct 4, 2016 · Viewed 7.9k times · Source

I'm trying to use URLComponents to compose a URL as that appears to be what it's for.

However, when I then access the url property of the components it is nil.

Example...

var urlComponents = URLComponents(string: "http://google.com")!
urlComponents.path = "auth/login"

Then I do ...

print(urlComponents)

Output...

scheme: http host: google.com path: auth/login
  - scheme : "http"
  - host : "google.com"
  - path : "auth/login"

But then...

print(urlComponents.url)

outputs nil.

Am I doing something wrong with this? How do I get the fully formed URL from all this? Thanks

Answer

user28434 picture user28434 · Oct 4, 2016

It looks like path parameter's string must start with /.

So change "auth/login" to "/auth/login" will do.