【问题标题】:URL init(string:relativeTo:) works wrong [duplicate]URL init(string:relativeTo:) 工作错误 [重复]
【发布时间】:2018-07-13 00:52:14
【问题描述】:

我正在尝试分 3 步构建复合 url,但结果是错误的!

// 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

预期结果:

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

即使我尝试像这样使用extendedURLabsoluteURL

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

我会得到同样的结果。

奇怪,但这种方法适用于其他一些不同的 URL。

【问题讨论】:

    标签: ios swift url path nsurl


    【解决方案1】:

    您应该先删除/ 以获得预期结果:

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

    更详细的解释可以看here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多