我的问题很简单。有人可以告诉我如何获取由UIWebView接收的URL中的查询字符串参数。目标c很容易,但我很快就需要一些帮助,因为我是新手。提前致谢。从Swift中的UIWebView中的URL获取查询字符串参数?
4
A
回答
9
在NSURL类中存在.query
属性,它返回字符串后的所有内容?在形式的网址:在这个例子中 http://www.example.com/index.php?key1=value1&key2=value2 使用的代码:
var url: NSURL = NSURL(string: "http://www.example.com/index.php?key1=value1&key2=value2")
println(url.query) // Prints: Optional("key1=value1&key2=value2")
更多信息在documentation
至于从UIWebView中获得的URL,你可以使用的线沿线的东西:
let url: NSURL = someWebView.NSURLRequest.URL
2
为了使它有点更容易得到你所期望的特定参数的值,你可以使用URLComponents
这将解析出查询字符串PARAMET你的。
例如,如果我们想查询字符串参数key2
在这个URL值:
“https://www.example.com/path/to/resource?key1=value1&key2=value2”
我们可以创建一个URLComponents结构,然后筛选查询项目与第一个匹配,并打印其值:
let url = URL(string: "https://www.example.com/path/to/resource?key1=value1&key2=value2")
if let url = url,
let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) {
let parameterWeWant = urlComponents.queryItems?.filter({ $0.name == "key2" }).first
print(parameterWeWant?.value ?? "")
}
关键(!)事情是urlComponents.queryItems
为我们返回了这个QueryItem
结构数组,这为我们提供了一种更简单的方法来过滤参数并获取我们要查找的参数的值。
▿ Optional([key1=value1, key2=value2])
▿ some: 2 elements
▿ key1=value1
- name: "key1"
▿ value: Optional("value1")
- some: "value1"
▿ key2=value2
- name: "key2"
▿ value: Optional("value2")
- some: "value2"
0
我们可以解析网址参数用这种方法,
func getParameterFrom(url: String, param: String) -> String? {
guard let url = URLComponents(string: url) else { return nil }
return url.queryItems?.first(where: { $0.name == param })?.value
}
let url = "http://www.example.com/index.php?key1=value1&key2=value2"
let key1 = self.getParameterFrom(url: url, param: "key1")
print("\(key1)") // value1
相关问题
- 1. 如何从Swift 3 xcode8的UIWebView中的url中获取查询字符串参数?
- 2. 从JavaScript中获取来自URL的查询字符串参数
- 3. 从url中获取参数字符串
- 4. 如何从JavaScript中的查询字符串URL中提取获取参数
- 5. 如何从PHP中的URL字符串提取查询参数?
- 6. 在AngularJS中获取URL参数查询字符串
- 7. 如何从codigniter的查询字符串中获取参数值
- 8. 获取UIWebView URL的查询
- 9. nextjs:如何从Next.js中的url获取GET(查询字符串)参数?
- 10. 从java上的查询字符串获取参数字符'#'
- 11. Owin获取查询字符串参数
- 12. 如何发送查询字符串作为获取参数swift
- 13. 从url中删除特定的查询字符串参数值
- 14. 从查询字符串中获取参数
- 15. 如何直接从查询字符串(URL)中获取Yii参数
- 16. 如何从字符串中获取查询字符串参数? LUA/nginx
- 17. 从URL字符串中提取查询字符串
- 18. 如何从C#中的相对URL字符串获取参数?
- 19. C#WebAPI - 获取URL作为查询字符串传递参数
- 20. PHP添加/修改查询字符串参数并获取URL
- 21. 获取托管bean中的查询字符串参数
- 22. 从javascript中的查询字符串中获取数据
- 23. 使用JavaScript从干净/ SEO友好的URL获取查询字符串参数
- 24. jquery从url中获取查询字符串
- 25. 如何从URL中获取查询字符串
- 26. 如何从URL中获取查询字符串
- 27. 从查询字符串获取数据
- 28. 获取URL查询字符串和PHP
- 29. 获取当前url查询字符串
- 30. 获取URL查询字符串不
有没有一种简单的方法,然后选择'key1'或'key2'价值? – tylerSF 2016-02-27 19:07:38
我想我可以做'let params = url.query;让splitParams = params!.componentsSeparatedByString(“=”)' – tylerSF 2016-02-27 19:21:31