本文介绍了获取URL参数的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用Swift从URL获取参数.假设我有以下网址:
I am trying to get the parameters from a URL using Swift. Let's say I have the following URL:
http://mysite3994.com?test1=blah&test2=blahblah
如何获取test1和test2的值?
How can I get the values of test1 and test2?
推荐答案
您可以使用以下代码获取参数
You can use the belowCode to get the param
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
}
}
}
这篇关于获取URL参数的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!