JUSDEV
JUSDEV

Reputation: 743

How to build a URL by using Dictionary in Swift

So I am messing around with the iMessages Framework, and in order to send data to another user the data must be sent as a URLComponents URL. However I can't figure out how to send a dictionary to use as the messages.url value.

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 anybody know how I can send the dictionary values as URLQueryItems in the URLComponents to save as the message.url ?

PS: I was wondering wether it would be possible to create an extension for the URL to store the dictionary in, that is what I am unsuccessfully trying atm.

Upvotes: 4

Views: 4595

Answers (3)

Max Potapov
Max Potapov

Reputation: 1337

Here is a code snippet to convert 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!)

Upvotes: 10

Ahmet Ardal
Ahmet Ardal

Reputation: 1172

You can use iMessageDataKit library. It's a tiny, useful MSMessage extension for setting/getting Int, Bool, Float, Double, String and Array values for keys.

It makes setting and getting data really easy 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)

Upvotes: 0

amir
amir

Reputation: 1332

You can use the following URLComponents extension:

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
            }) ?? [:]
        }
    }
}

And set the url components:

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

Upvotes: 2

Related Questions