【问题标题】:Swift & Firestore - appending dictionary to nested array using .arrayUnion()Swift & Firestore - 使用 .arrayUnion() 将字典附加到嵌套数组
【发布时间】:2020-06-25 21:40:34
【问题描述】:

我正在创建一个聊天应用程序,用户可以在其中与不同的人进行多次聊天(就像其他聊天应用程序一样)。我正在使用 Swift 和 Cloud Firestore

我的数据库设计如下:

Chat collection: [
     "chatMember": ["member1", "member2"],
     "createdAt" : Date().timeIntervalSince1970,
     "meesages" : []
]

一个聊天室会有'messages'数组,它会有消息dictionaries,也就是一个对象。

下面的代码是我尝试将消息字典附加到消息数组的地方。

Firebase 文档将.arrayUnion() LINK 引入文档>。 但它给了我一个错误说,

"上下文类型 '[Any]' 不能与字典文字一起使用"

@IBAction func sendBtnPressed(_ sender: UIButton) {

        if let messageBody = messageField.text, let messageSender = Auth.auth().currentUser?.email {

            db.collection("collectionName").document("docName").updateData([

//              FieldValue.arrayUnion() does not work for this case.

                K.FB.messages: FieldValue.arrayUnion([
                    "sender": messageSender,
                    "content": messageBody,
                    "createdAt": Date().timeIntervalSince1970
                ])
            ]) { ... closure }
        }
    }   

我在 Cloud Firestore 中找不到任何与 Swift 将字典附加到嵌套数组特别相关的信息。

我在 YouTube https://youtu.be/LKAXg2drQJQ> 上发现了一个非常相似的案例,但这是使用 Angular 制作的,它使用了 { ...curly bracket} 的对象。 FieldValue.arrayUnion() 似乎适用于其他语言,但不适用于 Swift。

如果有解决此问题的人能帮助我,那就太好了。

提前谢谢你。

【问题讨论】:

    标签: ios swift firebase dictionary google-cloud-firestore


    【解决方案1】:

    所以基本上你说的是这段代码:

    K.FB.messages: FieldValue.arrayUnion([
        "sender": messageSender,
        "content": messageBody,
        "createdAt": Date().timeIntervalSince1970
    ])
    

    是您想将 dictionary 附加到 array 中,名称在 K.FB.messages 常量中。但你真的不想这样做,甚至不可能。您想将 字典数组 附加到 数组。这意味着您必须将字典括在方括号中。如下图:

    K.FB.messages: FieldValue.arrayUnion([[
        "sender": messageSender,
        "content": messageBody,
        "createdAt": Date().timeIntervalSince1970
    ]])
    

    【讨论】:

      猜你喜欢
      • 2021-08-26
      • 2020-08-07
      • 2018-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-11
      • 2015-11-08
      • 2020-06-01
      相关资源
      最近更新 更多