好的,我正在使用 iMessage 应用程序,并尝试从此处所选消息中解析 1 个以上的 URL 查询项 - 我已成功在查询中获取/发送 1 个值:
override func willBecomeActive(with conversation: MSConversation) {
// Called when the extension is about to move from the inactive to active state.
// This will happen when the extension is about to present UI.
if(conversation.selectedMessage?.url != nil) //trying to catch error
{
let components = URLComponents(string: (conversation.selectedMessage?.url?.query?.description)!)
//let val = conversation.selectedMessage?.url?.query?.description
if let queryItems = components?.queryItems {
// process the query items here...
let param1 = queryItems.filter({$0.name == "theirScore"}).first
print("***************=> GOT IT ",param1?.value)
}
}
当我只有 1 个值时,只需打印 conversation.selectedMessage?.url?.query?.description
我就得到一个带有 1 个值的可选值,这很好。但对于多个,我找不到一种干净的方法来通过键获取特定值。
为 iMessage 解析给定键的 URLQueryItem
的正确方法是什么?
最佳答案
当您执行conversation.selectedMessage?.url?.query?.description
时,它只是打印出查询的内容。如果您有多个项目,那么它会显示如下:
item=Item1&part=Part1&story=Story1
您可以通过在“&”上拆分字符串,然后在“=”上拆分结果数组的内容来手动解析该字符串,以将各个键值对放入字典中。然后,您可以直接通过键引用每个值来获取具体值,如下所示:
var dic = [String:String]()
if let txt = url?.query {
let arr = txt.components(separatedBy:"&")
for item in arr {
let arr2 = item.components(separatedBy:"=")
let key = arr2[0]
let val = arr2[1]
dic[key] = val
}
}
print(dic)
上面为您提供了一种通过键访问值的简单方法。然而,这有点冗长。您在代码中提供的方式(在 queryItems
数组上使用过滤器)是更紧凑的解决方案:) 因此您已经有了更简单/紧凑的解决方案,但如果这种方法对您个人来说更有意义,你总是可以走这条路...
此外,如果问题是您必须多次编写相同的过滤代码才能从 queryItems
数组中获取值,那么您始终可以使用一个带有两个参数的辅助方法,即queryItems
数组和一个 String
参数(键),并返回一个可选的 String
值(与键匹配的值),如下所示:
func valueFrom(queryItems:[URLQueryItem], key:String) -> String? {
return queryItems.filter({$0.name == key}).first?.value
}
那么上面的代码将如下所示:
if let queryItems = components?.queryItems {
// process the query items here...
let param1 = valueFrom(queryItems:queryItems, key:"item")
print("***************=> GOT IT ", param1)
}
关于swift - 如何在 Swift 中传递和获取多个 URL QueryItem?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43335667/