58

I can't understand what's the difference between these two ways of calling:

NSURLComponents(URL: url, resolvingAgainstBaseURL: true)

and

NSURLComponents(URL: url, resolvingAgainstBaseURL: false)

And I found the explanation of documentation was hard to understand... Can someone please give me a simple example to show how this api works? (I tried many different combinations of parameters , but what they yielded were same...)

Honey
  • 24,125
  • 14
  • 123
  • 212
SomeHowWhite
  • 621
  • 5
  • 9

1 Answers1

92

It makes only a difference if you create the URL components from an NSURL which was created relative to another NSURL:

let baseURL = NSURL(string: "http://server/foo/")!
let url = NSURL(string: "bar/file.html", relativeToURL: baseURL)!
print(url.absoluteString)
// "http://server/foo/bar/file.html"

With resolvingAgainstBaseURL == false, the URL components represent only the relative part of the URL:

let comp1 = NSURLComponents(URL: url, resolvingAgainstBaseURL: false)!
print(comp1.string!)
// "bar/file.html"

With resolvingAgainstBaseURL == true, the URL components represent the fully resolved URL:

let comp2 = NSURLComponents(URL: url, resolvingAgainstBaseURL: true)!
print(comp2.string!)
// "http://server/foo/bar/file.html"
Martin R
  • 488,667
  • 78
  • 1,132
  • 1,248