gpt4 book ai didi

ios - 如何将 url.query 转换为 Swift 中的字典?

转载 作者:搜寻专家 更新时间:2023-10-30 22:22:15 26 4
gpt4 key购买 nike

我有一个 URL 进入 AppDelegate 方法:

func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
}

URL 类似于 www.wesite.com/shareplace.html?placeid=123

如何将其转换为字典以便于访问?

我在某些网站上找到了一些代码,但它在 Xcode 9 中显示错误:

 extension URL {
var queryDictionary: [String: AnyObject]? {
return URLComponents(url: self, resolvingAgainstBaseURL: false)?
.queryItems?
.reduce([:], combine: { (var result: [String: AnyObject], queryItem) -> [String: AnyObject] in
if queryItem.value?.containsString(",") ?? false {
let array = queryItem.value?.componentsSeparatedByString(",")

result[queryItem.name] = array
}
else {
result[queryItem.name] = queryItem.value
}

return result
})
}
}

.reduce([:], combine: { (var result: [String: AnyObject], queryItem)
-> [String: AnyObject] in
(var result) Parameters may not have the 'var' specifier

最佳答案

简单扩展

extension URL {
var queryDictionary: [String: String]? {
guard let query = self.query else { return nil}

var queryStrings = [String: String]()
for pair in query.components(separatedBy: "&") {

let key = pair.components(separatedBy: "=")[0]

let value = pair
.components(separatedBy:"=")[1]
.replacingOccurrences(of: "+", with: " ")
.removingPercentEncoding ?? ""

queryStrings[key] = value
}
return queryStrings
}
}

用法

let urlString = "http://www.youtube.com/video/4bL4FI1Gz6s?hl=it_IT&iv_logging_level=3&ad_flags=0&endscreen_module=http://s.ytimg.com/yt/swfbin/endscreen-vfl6o3XZn.swf&cid=241&cust_gender=1&avg_rating=4.82280613104"
let url = URL(string: urlString)
print(url!.queryDictionary ?? "NONE")

关于ios - 如何将 url.query 转换为 Swift 中的字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46603220/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com