Search code examples
iosswiftfirebasefirebase-realtime-databaseuuid

iOS Firebase -How to create multi node location update using .childByAutoId()


I send data to a single child location using iOS' UUID().uuidString:

let userPostsRef = db?.child("users")?.child(\(uid))?.child("posts")?.child(theUUID) // uuid is basically the postId
userPostsRef.updateChildValues(userDict)

If I want to send data to multiple nodes I have to structure the node children differently:

let userPostsRef = "/users/\(uid)/posts/\(postId)"
let postRef = "/posts/\(uid)/\(postId)"

Using the first way I can get a reference to the UUID and send the uuid as a key/value pair as part of a dictionary to whatever node. But doing it the second way I can't get access to .childByAutoId() because there isn't a ref to start from.

How can I create a multi location update using Firebase's .childByAutoId() and get a reference to it instead of a UUID().uuidString?

let postId = UUID().uuidString // instead of uuidString I want to use .childByAutoId instead
let db = Database.database().reference()
let uid = Auth.auth().currentUser?.uid

@IBAction fileprivate func postButtonTapped(_ sender: UIButton) {

     var userDict = [String:Any]()
     // instead of sending self.postId I want to send .childByAutoId
     userDict.updateValue(self.postId, forKey: "postId")
     userDict.updateValue(commentTextField.text! forKey: "comment")             

     var postDict = [String:Any]()
     postDict.updateValue(commentTextField.text! forKey: "comment")

    let userPostsRef = "/users/\(uid)/posts/\(postId)"
    let postRef = "/posts/\(uid)/\(postId)"

    let multiNodeDict = [String:Any]()
    multiNodeDict.updateValue(userDict, forKey: userPostsRef)
    multiNodeDict.updateValue(postDict, forKey: postRef)

    db.updateChildValues(multiNodeDict)
}

Solution

  • The childByAutoId() method is a pure client-side operation. It doesn't create a child node in the database, but merely generates a unique location based on a key that is statistically guaranteed to be unique. In that sense it's quite similar to a UUID, just with some special properties (such as being timestamp-based) that makes the more appealing as database keys.

    This means that you can call childByAutoId() and just take the key from it as your postId:

    let postId = db.childByAutoId().key