Search code examples
iosswiftswift3ios10imessage

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.


Solution

  • 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!)