如何在Swift中使用Dictionary构建URL

JUS*_*DEV 4 ios imessage swift swift3 ios10

所以我正在搞乱iMessages框架,为了将数据发送给另一个用户,数据必须作为一个发送URLComponents URL.但是我无法弄清楚如何发送字典作为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")
    })
}
Run Code Online (Sandbox Code Playgroud)

有谁知道我可以送字典值URLQueryItemsURLComponents保存的message.url

PS:我想知道是否可以创建URL的扩展来存储字典,这就是我尝试atm失败的原因.

Max*_*pov 9

这是一个将字典转换为的代码片段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!)
Run Code Online (Sandbox Code Playgroud)