简体   繁体   English

iOS Firebase-如何使用.childByAutoId()创建多节点位置更新

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

I send data to a single child location using iOS' UUID().uuidString : 我使用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. 使用第一种方法,我可以获得对UUID的引用,并将uuid作为键/值对作为字典的一部分发送到任何节点。 But doing it the second way I can't get access to .childByAutoId() because there isn't a ref to start from. 但是以第二种方式进行.childByAutoId()因为没有引用开始,所以我无法访问.childByAutoId()

How can I create a multi location update using Firebase's .childByAutoId() and get a reference to it instead of a UUID().uuidString ? 如何使用Firebase的.childByAutoId()创建多位置更新,并获取对它的引用而不是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)
}

The childByAutoId() method is a pure client-side operation. childByAutoId()方法是纯客户端操作。 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. 从这个意义上讲,它与UUID非常相似,只是具有一些特殊的属性(例如基于时间戳),这些属性使它们作为数据库密钥更具吸引力。

This means that you can call childByAutoId() and just take the key from it as your postId : 这意味着您可以调用childByAutoId()并将其中的键用作您的postId

let postId = db.childByAutoId().key

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM