88

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...)

mfaani
  • 33,269
  • 19
  • 164
  • 293
SomeHowWhite
  • 931
  • 1
  • 6
  • 9

1 Answers1

147

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
  • 529,903
  • 94
  • 1,240
  • 1,382