Retrieve randomly generated child ID from Firebase

前端 未结 4 1442
青春惊慌失措
青春惊慌失措 2021-02-03 12:53

I have Firebase generating random keys for my records in a Swift app. How do I go about retrieving that key if I want to change a specific record? In my example below, I\'m mark

相关标签:
4条回答
  • 2021-02-03 13:10

    Following Tim's answer for Swift 3 and Firebase 4 I had to use the below

    for task in snapshot.children {
                guard let taskSnapshot = task as? DataSnapshot else {
                    continue
                }
    
                let id = taskSnapshot.key
    
    0 讨论(0)
  • 2021-02-03 13:18

    To create a randomly generated key you need to use childByAutoId() (which I can't see in your example code).
    This will return a Firebase reference you could use and which will return the key with it's .key property

    var post1Ref = ref.childByAutoId()
    post1Ref.setValue(post1)
    
    var postId = post1Ref.key
    

    See documentation here

    0 讨论(0)
  • 2021-02-03 13:33

    An alternative to Ron's answer involves generating the key first and then using it to set value:

    let autoId = databaseReference.childByAutoId().key
    databaseReference.child(autoId).setValue(YOUR_VALUE)
    
    0 讨论(0)
  • 2021-02-03 13:36
    tasksRef.observeSingleEventOfType(.Value, withBlock: { snapshot in
        for task in snapshot.children {
            guard let taskSnapshot = task as? FDataSnapshot else {
                continue
            }
    
            let id = task.key
            // do other things
        }
    }
    
    0 讨论(0)
提交回复
热议问题