Lance Samaria
Lance Samaria

Reputation: 19612

Swift Firebase -How to generate different .childByAutoId keys when using Fan Out

I have a chat system inside my app. When the user presses send to send the message data to different nodes inside the database -it works fine. The issue I'm having is since I'm using fan out I generate the .childByAutoIdkey before the data is sent. The user presses a send button to start the process but it's always the same exact .childByAutoId key so I'm just overwriting the previous message data. If the user pops the vc and comes back to it then a new key is created but obviously that's terrible ux for a messaging system?

How can I generate different .childByAutoId keys every time the user presses send to fan out?

@obj func sendMessageButtonPressed() {

    // ***here's the problem, every time they press send, it's the same exact childByAutoId().key so I'm just overwriting the previous data at the messages/messageId path
    guard let messageId = FirebaseManager.Database.database().reference().child("messages")?.childByAutoId().key else { return }

    var messageIdDict: [String: Any] = [messageId: "1"]

    var messageDict = [String: Any]() // has the fromId, toId, message, and timeStamp on it

    let messageIdPath = "messages/\(messageId)"
    let fromIdPath = "user-messages/\(currentUserId)"
    let toIdPath = "user-messages/\(toId)"

    var fanOutDict = [String: Any]()
    fanOutDict.updateValue(messageDict, forKey: messageIdPath)
    fanOutDict.updateValue(messageIdDict, forKey: fromIdPath)
    fanOutDict.updateValue(messageIdDict, forKey: toIdPath) 

    let rootRef = Database.database().reference()
    rootRef?.updateChildValues(fanOutDict)
}

Upvotes: 0

Views: 72

Answers (1)

Lance Samaria
Lance Samaria

Reputation: 19612

The problem wasn't a new key was not getting generated. @FrankvanPuffelen pointed out in th comments that a new key should get generated every time which is exactly what was happening.

The problem was the fanout was overwriting what was originally written at these 2 paths:

let fromIdPath = "user-messages/\(currentUserId)"
let toIdPath = "user-messages/\(toId)"

It appeared the key was the same because the data kept getting overwritten.

The way I was generating the key works fine

Upvotes: 1

Related Questions