【问题标题】:Get Value of URL Parameters [duplicate]获取 URL 参数的值 [重复]
【发布时间】:2020-10-12 16:18:02
【问题描述】:

我正在尝试使用 Swift 从 URL 获取参数。假设我有以下网址:

https://test.page.link/foo?accessCode=GA362078&bar=test

如何获得foo?accessCode (GA362078) 和bar (test) 的值?

【问题讨论】:

标签: ios swift url


【解决方案1】:

使用URLComponentsqueryItems

func value(for name: String, in urlString: String, with path: String) -> String? {
    if let components = URLComponents.init(string: urlString) {
        if components.path == path {
            return components.queryItems?.first { $0.name == name }?.value
        }
        else {
            return("Not found")
        }
    }

    return nil
}

let urlString  = "https://test.page.link/foo?accessCode=GA362078&bar=test"

if let accessCodeValue = value(for: "accessCode", in: urlString, with: "/foo") {
    print(accessCodeValue)
}

输出:

GA362078

【讨论】:

  • 在最近的 Swift 中使用 URLComponents 而不是 NSURLComponents 怎么样?
  • 有没有办法在方法参数中传递“foo”以返回“GA362078”,同时还能够传入“bar”来获取“test”?
  • @Han 只需获取 QueryItem 属性(名称 items[0].name 和值 items[0].value)。顺便说一句/foo 是路径不是查询项
  • @koen 只需返回first {$0.name == name }?.value
  • 这取决于你。我喜欢使用扩展来避免重复代码,但正如你所说,这只是一行。
猜你喜欢
  • 2013-04-09
  • 1970-01-01
  • 2016-03-05
  • 1970-01-01
  • 2014-07-18
  • 2012-09-02
  • 2013-07-04
  • 2022-01-18
  • 2016-06-28
相关资源
最近更新 更多