我正在尝试使用Swift从URL获取参数。假设我有以下网址:
http://mysite3994.com?test1=blah&test2=blahblah
如何获取test1和test2的值?
您可以使用以下代码获取参数
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")
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 } } }