iosswiftnsurlnsurlcomponents

URLComponents.url is nil


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


Solution

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

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