如何从QueryString获取KeyValue并以特定的字符串格式返回字符串

时间:2017-08-29 09:31:51

标签: swift3

我是新手,需要帮助。 我需要从下面的QueryString创建一个baseString。 这个baseString最终会看起来像这样:

& ap =裕廊坊心邻坊& oq = c #nunit mac& q = c #nunit mac

QueryString:

Foo

问题:

如何从上面的QueryString中获取KeyValue

1)通过"&"将所有组件分开。如下所示

- 查询字符串中的键值:

q = c%23 + nunit + mac& oq
oq = c%23 + nunit + mac
AP =裕坊%20邻坊

HTTPS://www.sky.com/api/v1/rest/level2/in-in/?q=c%23+nunit+mac&oq=c%23+nunit+mac&ap=裕坊%20邻坊

感谢。非常感谢你的帮助。

1 个答案:

答案 0 :(得分:0)

您可以在URLQueryItem类的帮助下从URL的查询项中获取Key-Value字典,如下所示

let urlString = "https://www.sky.com/api/v1/rest/level2/in-in/?q=c%23+nunit+mac&oq=c%23+nunit+mac&ap=裕坊%20邻坊"
let encodedUrlString = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!

let items = URLComponents(string: encodedUrlString)?.queryItems
var keyValues: [String: String] = [:]
items?.forEach{
    item in
    keyValues[item.name] = item.value
}
print(keyValues)
//["q": "c%23+nunit+mac", "ap": "裕坊%20邻坊", "oq": "c%23+nunit+mac"]

希望这会对你有所帮助。 如果需要从url字符串中获取Query子字符串,则需要从中创建URL并获取查询。

guard let url = URL(string: encodedUrlString) else {
    fatalError()
}
let queryString = url.query!
print(queryString.removingPercentEncoding)
//q=c%23+nunit+mac&oq=c%23+nunit+mac&ap=裕坊%20邻坊

如果您需要在查询中添加新组件,

var components = URLComponents(string: encodedUrlString)
let item = URLQueryItem(name: "NEWVKEY", value: "NEWVALUE")
components?.queryItems?.append(item)

let url = components?.url
let resultString = url?.absoluteString
//or
let resultString2 = url?.absoluteString.removingPercentEncoding

这个想法是使用Swift标准库的URL处理能力。请查看URL,URLComponents,URLQueryItem结构的文档。不要编写字符串处理代码,而是操纵URL。

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