swift - 初始化 NSURLComponents 实例时将 false 和 true 传递给 'resolvingAgainstBaseURL' 有什么区别?

标签 swift url nsurl nsurlcomponents

我不明白这两种调用方式有什么区别:

NSURLComponents(URL: url, resolvingAgainstBaseURL: true)

NSURLComponents(URL: url, resolvingAgainstBaseURL: false)

而且我发现文档的解释很难理解...... 有人可以给我一个简单的例子来说明这个 api 是如何工作的吗? (我尝试了许多不同的参数组合,但它们产生的结果是相同的......)

最佳答案

只有从 NSURL 创建 URL 组件才会有所不同 是相对于另一个 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"

使用 resolvingAgainstBaseURL == false,URL 组件 仅代表 URL 的相关部分:

let comp1 = NSURLComponents(URL: url, resolvingAgainstBaseURL: false)!
print(comp1.string!)
// "bar/file.html"

使用 resolvingAgainstBaseURL == true,URL 组件 表示完全解析的 URL:

let comp2 = NSURLComponents(URL: url, resolvingAgainstBaseURL: true)!
print(comp2.string!)
// "http://server/foo/bar/file.html"

关于swift - 初始化 NSURLComponents 实例时将 false 和 true 传递给 'resolvingAgainstBaseURL' 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38720933/

相关文章:

ios - 在不同 VC 之间移动时管理 UIView 动画

ios - iOS 中 G2、D♯3、D3 的 hexa MIDI 消息是什么?

java - 转换和验证来自不受信任来源的 url

http - URL 中的 URL 编码尖括号?

ios - 从 Swift 打开 Instagram 图片

macos - 如何确定 NSURL 是否具有安全范围信息?

swift - 无法在 View Controller 和 TableView Controller 之间快速发送 int 值

ios - 无法添加标签以查看

java - JAVA 中 URL 背后的逻辑

iphone - 带大括号的 NSURL