Search code examples
iosswifturlpathnsurl

URL init(string:relativeTo:) works wrong


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.


Solution

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