获取 URL 参数值

发布
更新
字数 83
阅读 1 分钟
阅读量 2073

通过解析 URLComponents 获取 URL 参数。

extension URL {
    /// Query: `?foo=bar` uses `valueOf("foo")`
    func valueOf(_ queryParameterName: String) -> String? {
        guard let components = URLComponents(url: self, resolvingAgainstBaseURL: true) else { return nil }

        return components.queryItems?.first(where: { $0.name == queryParameterName })?.value
    }
}

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

参考

https://developer.apple.com/documentation/foundation/urlcomponents/