Firebase Unique Value

后端 未结 1 2005
不知归路
不知归路 2020-12-20 09:14

Having the following structure in Firebase:

-events
     -Firebase Push ID for Event 1
         **-key: \"DF2342\"**
         -name: \"Event 1\"
         -cr         


        
相关标签:
1条回答
  • 2020-12-20 09:57

    Since your application requires that you can't use childByAutoId, a way to make sure you're generating unique IDs would be to store an additional table in firebase of just the IDs you've generated. For example:

    "keys": {
      "DF2342": true,
      "AB1232": true,
      ...
    }
    

    Then when you generate your key you can do something like this:

    let boardKey = self.keyGenHelper.generateUniqueKey()
    var validData = false
    while(!validData){
    // check /keys in the database to see if we've already generated a key of this value
    databaseRef?.child("keys").queryEqual(toValue: boardKey).observeSingleEvent(of: .childAdded, with: { (snapshot) in
        if !snapshot.exists() {
            let boardIdRef = self.databaseRef!.child("events").childByAutoId()
            boardIdRef.setValue(board.generateDictionary(key: boardKey))
            completion(boardKey, boardIdRef.key)
            validData = true
        }
    }, withCancel: {(error) in
        print(error)
    })
    

    You also need to make sure you're writing the newly generated key to /keys.

    0 讨论(0)
提交回复
热议问题