我有以下网址查询:
encodedMessage=PD94bWwgdmVyNlPg%3D%3D&signature=kcig33sdAOAr%2FYYGf5r4HGN
如何拆分查询以获取encodedMessage
和signature
值?
答案 0 :(得分:8)
实现这一目标的正确方法是使用URLComponents:
一种用于解析基于RFC 3986的URL并构建的结构 来自其组成部分的URL。
通过获取网址组件host字符串和queryItems数组,如下所示:
if let urlComponents = URLComponents(string: "http://mydummysite.com?encodedMessage=PD94bWwgdmVyNlPg%3D%3D&signature=kcig33sdAOAr%2FYYGf5r4HGN"), let host = urlComponents.host, let queryItems = urlComponents.queryItems {
print(host) // mydummysite.com
print(queryItems) // [encodedMessage=PD94bWwgdmVyNlPg==, signature=kcig33sdAOAr/YYGf5r4HGN]
}
queryItems
数组包含URLQueryItem个对象,其中包含name
和value
个属性:
if let urlComponents = URLComponents(string: "http://mydummysite.com?encodedMessage=PD94bWwgdmVyNlPg%3D%3D&signature=kcig33sdAOAr%2FYYGf5r4HGN"),let queryItems = urlComponents.queryItems {
// for example, we will get the first item name and value:
let name = queryItems[0].name // encodedMessage
let value = queryItems[0].value // PD94bWwgdmVyNlPg==
}
同时强>
如果您在没有完整网址的情况下获得查询,我建议通过添加虚拟主机作为查询字符串的前缀来执行一个非常简单的技巧,如下所示:
let myQuery = "encodedMessage=PD94bWwgdmVyNlPg%3D%3D&signature=kcig33sdAOAr%2FYYGf5r4HGN"
let myDummyUrlString = "http://stackoverflow.com?" + myQuery
if let urlComponents = URLComponents(string: myDummyUrlString),let queryItems = urlComponents.queryItems {
// for example, we will get the first item name and value:
let name = queryItems[0].name // encodedMessage
let value = queryItems[0].value // PD94bWwgdmVyNlPg==
} else {
print("invalid url")
}
答案 1 :(得分:3)
您可以通过这种方式获取键值对:
let str = "encodedMessage=PD94bWwgdmVyNlPg%3D%3D&signature=kcig33sdAOAr%2FYYGf5r4HGN"
let arr = str.components(separatedBy:"&")
var data = [String:Any]()
for row in arr {
let pairs = row.components(separatedBy:"=")
data[pairs[0]] = pairs[1]
}
let message = data["encodedMessage"]
let sig = data["signature"]
我不确定这是不是你在寻找什么。如果不是,你能否进一步澄清一下你在寻找什么?