所以我在搞乱 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")
})
}
有人知道如何将字典值作为 URLComponents
中的 URLQueryItems
发送以保存为 message.url
吗?
PS:我想知道是否可以为 URL 创建一个扩展名来存储字典,这就是我尝试 atm 失败的原因。
最佳答案
这是将字典转换为 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!)
关于ios - 如何在 Swift 中使用字典构建 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39594265/