ios - 如何在 Swift 中使用字典构建 URL

标签 ios swift swift3 ios10 imessage

所以我在搞乱 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/

相关文章:

iOS 试飞 "There was an error loading your builds."

ios - 我不能用字符串类型的参数列表调用?

ios - 如何将 Objective-C 静态扩展库链接/嵌入到 Xcode 13 项目中?

ios - Swift UICollectionView 单元格宽度

iphone - InAppPurchase 无效的产品标识符 - 可能的原因

objective-c - 在 Objective-C 中将八进制字符串转换为十进制?

应用重新安装后的 iOS 位置权限

ios - 使用 URL 将 Plist 文件加载到数组中

json - 单击保存按钮时如何更改存储的 JSON 数据? swift 3

ios - Swift 3 - 将导航项添加到 UINavigationController 子类