2

I'm trying to build a compound url in 3 steps, but the result is wrong!

// 1)
let baseURL = URL(string: "http://clapps.clappsa.com")!
print(baseURL.absoluteString)
// http://clapps.clappsa.com

// 2)
let extendedURL = baseURL.appendingPathComponent("public", isDirectory: true)
print(extendedURL.absoluteString)
// http://clapps.clappsa.com/public/

// 3)
let finalURL = URL(string: "/img/3-mentee.jpg", relativeTo: extendedURL)!
print(finalURL.absoluteString)
// http://clapps.clappsa.com/img/3-mentee.jpg

Expected result:

http://clapps.clappsa.com/public/img/3-mentee.jpg

Even if I try to use the absoluteURL of the extendedURL like this:

let finalURL = URL(string: "/img/3-mentee.jpg", relativeTo: extendedURL.absoluteURL)!
print(finalURL.absoluteString)
// http://clapps.clappsa.com/img/3-mentee.jpg

I will get the same result.

Strange, but such approach works ok with some other different URLs.

kelin
  • 11,323
  • 6
  • 67
  • 104

1 Answers1

5

You should remove first / to get expected result:

let finalURL = URL(string: "img/3-mentee.jpg", relativeTo: extendedURL)!
print(finalURL.absoluteString) // http://clapps.clappsa.com/public/img/3-mentee.jpg

More detail explanation can be found here.

pacification
  • 5,838
  • 4
  • 29
  • 51