ios 获取URL参数的值

hts6caw3  于 2022-11-19  发布在  iOS
关注(0)|答案(5)|浏览(289)

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

http://mysite3994.com?test1=blah&test2=blahblah

如何获得test1和test2的值?

cld4siwp

cld4siwp1#

您可以使用下面的代码来获取参数

func getQueryStringParameter(url: String, param: String) -> String? {
  guard let url = URLComponents(string: url) else { return nil }
  return url.queryItems?.first(where: { $0.name == param })?.value
}

let test1 = getQueryStringParameter(url, param: "test1")一样调用方法

其他方法,带扩展名:

extension URL {
    public var queryParameters: [String: String]? {
        guard
            let components = URLComponents(url: self, resolvingAgainstBaseURL: true),
            let queryItems = components.queryItems else { return nil }
        return queryItems.reduce(into: [String: String]()) { (result, item) in
            result[item.name] = item.value
        }
    }
}
vshtjzan

vshtjzan2#

**步骤1:**创建URL扩展

extension URL {
    func valueOf(_ queryParameterName: String) -> String? {
        guard let url = URLComponents(string: self.absoluteString) else { return nil }
        return url.queryItems?.first(where: { $0.name == queryParameterName })?.value
    }
}

**步骤2:**如何使用扩展

let newURL = URL(string: "http://mysite3994.com?test1=blah&test2=blahblah")!

newURL.valueOf("test1") // Output i.e "blah"
newURL.valueOf("test2") // Output i.e "blahblah"
nfs0ujit

nfs0ujit3#

我还做了一个URL扩展,但将查询参数查找放入了一个下标。

extension URL {
    subscript(queryParam:String) -> String? {
        guard let url = URLComponents(string: self.absoluteString) else { return nil }
        return url.queryItems?.first(where: { $0.name == queryParam })?.value
    }
}

用法:

let url = URL(string: "http://some-website.com/documents/127/?referrer=147&mode=open")!

let referrer = url["referrer"]  // "147"
let mode     = url["mode"]      // "open"
irlmq6kh

irlmq6kh4#

当链接指向在Angular上创建的网站时,似乎所有现有的答案都不起作用,这是因为Angular的路径通常在所有链接中都包含#(散列)符号,这导致url.queryItems总是返回nil。
如果链接如下所示:http://example.com/path/#/morepath/aaa?test1=blah&test2=blahblah
那么参数只能从url.fragment中获得。在@Matt的扩展中添加一些额外的解析逻辑后,一个更通用的代码看起来像这样:

extension URL {
    subscript(queryParam: String) -> String? {
        guard let url = URLComponents(string: self.absoluteString) else { return nil }
        if let parameters = url.queryItems {
            return parameters.first(where: { $0.name == queryParam })?.value
        } else if let paramPairs = url.fragment?.components(separatedBy: "?").last?.components(separatedBy: "&") {
            for pair in paramPairs where pair.contains(queryParam) {
                return pair.components(separatedBy: "=").last
            }
            return nil
        } else {
            return nil
        }
    }
}

用法保持不变:

let url = URL(string: "http://example.com/path/#/morepath/aaa?test1=blah&test2=blahblah")!

let referrer = url["test1"]  // "blah"
let mode     = url["test2"]  // "blahblah"
7lrncoxx

7lrncoxx5#

另一种方法是在URL上创建一个扩展以返回组件,然后在[URLQueryItem]上创建一个扩展以从queryItems中检索值。

extension URL {
    var components: URLComponents? {
        return URLComponents(url: self, resolvingAgainstBaseURL: false)
    }
}

extension Array where Iterator.Element == URLQueryItem {
    subscript(_ key: String) -> String? {
        return first(where: { $0.name == key })?.value
    }
}

这是一个如何使用的例子:

if let urlComponents = URL(string: "http://mysite3994.com?test1=blah&test2=blahblah")?.components,
    let test1Value = urlComponents.queryItems?["test1"] {
    print(test1Value)
}

相关问题