【问题标题】:What's the difference between passing false and true to 'resolvingAgainstBaseURL' when initialize a NSURLComponents instance?初始化 NSURLComponents 实例时将 false 和 true 传递给“resolvingAgainstBaseURL”有什么区别?
【发布时间】:2016-12-07 20:06:06
【问题描述】:

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

NSURLComponents(URL: url, resolvingAgainstBaseURL: true)

NSURLComponents(URL: url, resolvingAgainstBaseURL: false)

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

【问题讨论】:

    标签: swift url nsurl nsurlcomponents


    【解决方案1】:

    如果您从 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"
    

    【讨论】:

    • 尽可能准确的答案
    猜你喜欢
    • 2011-01-20
    • 2013-01-13
    • 1970-01-01
    • 2018-12-20
    • 1970-01-01
    • 1970-01-01
    • 2014-03-16
    • 1970-01-01
    • 2011-10-14
    相关资源
    最近更新 更多