How to create url using dictionary in Swift

So, I messed around with the iMessagesFramework, and to send data to another user, the data must be sent as URLComponents URL. However, I cannot figure out how to send a dictionary to use as a value messages.url.

func createMessage(data: dictionary) {

    /*

     The Dictionary has 3 values, 1 string and two arrays. 

    let dictionary = ["title" : "Title Of Dictionary", "Array1" : [String](), "Array2" : [String]() ] as [String : Any]

    */ 


    let components = URLComponents()

    let layout = MSMessageTemplateLayout()
    layout.image = UIImage(named: "messages-layout.png")!
    layout.imageTitle = "\(dictionary["title"])"

    let message = MSMessage()
    message.url = components.url!
    message.layout = layout

    self.activeConversation?.insert(message, completionHandler: { (error: Error?) in
        print("Insert Message")
    })
}

Does anyone know how I can send dictionary values ​​as URLQueryItemsin URLComponentsto save as message.url?

PS: I was wondering if it is possible to create an extension for the dictionary storage URL, this is what I am trying to attack unsuccessfully.

+4
source share
3 answers

Here is a code snippet for converting a dictionary to URLQueryItems:

let dictionary = [
    "name": "Alice",
    "age": "13"
]

func queryItems(dictionary: [String:String]) -> [URLQueryItem] {
    return dictionary.map {
        // Swift 3
        // URLQueryItem(name: $0, value: $1)

        // Swift 4
        URLQueryItem(name: $0.0, value: $0.1)
    }
}

var components = URLComponents()
components.queryItems = queryItems(dictionary: dictionary)
print(components.url!)
+7

URLComponents:

extension URLComponents{
    var queryItemsDictionary : [String:Any]{
        set (queryItemsDictionary){
            self.queryItems = queryItemsDictionary.map {
                URLQueryItem(name: $0, value: "\($1)")
            }
        }
        get{
            var params = [String: Any]()
            return queryItems?.reduce([:], { (_, item) -> [String: Any] in
                params[item.name] = item.value
                return params
            }) ?? [:]
        }
    }
}

URL:

var url = URLComponents()
url.queryItemsDictionary = ["firstName"   : "John",
                            "lastName"    : "Appleseed"]
+1

You can use the iMessageDataKit library. This small, useful extension MSMessageto set / get the values Int, Bool, Float, Double, Stringand Arrayfor the keys.

It simplifies the configuration and retrieval of data:

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 am the author iMessageDataKit)

0
source

Source: https://habr.com/ru/post/1655189/


All Articles