What's the difference between passing false and true to 'resolvingAgainstBaseURL' when initialize a NSURLComponents instance?

SwiftUrlNsurlNsurlcomponents

Swift Problem Overview


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

Swift Solutions


Solution 1 - Swift

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"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSomeHowWhiteView Question on Stackoverflow
Solution 1 - SwiftMartin RView Answer on Stackoverflow