How to pass and get multiple URLQueryItems in Swift?

心已入冬 提交于 2019-12-06 09:05:51

When you do conversation.selectedMessage?.url?.query?.description it simply prints out the contents of the query. If you have multiple items then it would appear something like:

item=Item1&part=Part1&story=Story1

You can parse that one manually by splitting the string on "&" and then splitting the contents of the resulting array on "=" to get the individual key value pairs in to a dictionary. Then, you can directly refer to each value by key to get the specific values, something like this:

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)

The above gives you an easy way to access the values by key. However, that is a bit more verbose. The way you provided in your code, using a filter on the queryItems array, is the more compact solution :) So you already have the easier/compact solution, but if this approach makes better sense to you personally, you can always go this route ...

Also, if the issue is that you have to write the same filtering code multiple times to get a value from the queryItems array, then you can always have a helper method which takes two parameters, the queryItems array and a String parameter (the key) and returns an optional String value (the value matching the key) along the following lines:

func valueFrom(queryItems:[URLQueryItem], key:String) -> String? {
    return queryItems.filter({$0.name == key}).first?.value
}

Then your above code would look like:

if let queryItems = components?.queryItems {
    // process the query items here...
    let param1 = valueFrom(queryItems:queryItems, key:"item")
    print("***************=>    GOT IT ", param1)
}

You can use iMessageDataKit library. It makes setting and getting data really easy and straightforward like:

let message: MSMessage = MSMessage()

message.md.set(value: 7, forKey: "user_id")
message.md.set(value: "john", forKey: "username")
message.md.set(values: ["joy", "smile"], forKey: "tags")

print(message.md.integer(forKey: "user_id")!)
print(message.md.string(forKey: "username")!)
print(message.md.values(forKey: "tags")!)

(Disclaimer: I'm the author of iMessageDataKit)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!