k1nate
k1nate

Reputation: 83

Swift & Firestore - appending dictionary to nested array using .arrayUnion()

I am creating a chat application where a user can start multiple chats with a different person (just like the rest of the other chat apps). I'm using Swift with Cloud Firestore.

My database design is the following:

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

One chat room will have 'messages' array and it will have message dictionaries aka an object.

Below code is where I am trying to append the message dictionary to the messages array.

The Firebase doc introduces .arrayUnion() <LINK to the document>. But it gives me an error saying,

"Contextual type '[Any]' cannot be used with dictionary literal"

@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 }
        }
    }   

I can't find any information specifically related to Swift's appending Dictionary to nested array in the Cloud Firestore.

I found a very similar case on YouTube <https://youtu.be/LKAXg2drQJQ> but this is made with Angular which uses an object with { ...curly bracket}. FieldValue.arrayUnion() seems to work on other languages but not Swift.

It'd be awesome if someone who has resolved this issue would help me out.

Thank you in advance.

Upvotes: 2

Views: 1503

Answers (1)

lacefarin
lacefarin

Reputation: 1234

So basically what you're saying with this code:

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

is that you want to append dictionary to array with name that is in K.FB.messages constant. But you don't really want to do that and it isn't even possible. You want to append array of dictionaries to array. This means that you must enclose your dictionary in a square brackets. Like shown below:

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

Upvotes: 4

Related Questions