Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

swift - Firebase Unique Value

Having the following structure in Firebase:

-events
     -Firebase Push ID for Event 1
         **-key: "DF2342"**
         -name: "Event 1"
         -createdOn : 12/12/12
     -Firebase Push ID for Event 2
         **-key: "AB1232"**
         -name: "Event 1"
         -createdOn : 12/12/12

Every key is autogenerated locally (DF2342 and AB1232) by the device where the app is running on although, I want to generate the key first on the device, then check if the key already exists in firebase database. If it does exist regenerate the key and try again. Here the code I'm using for that:

 let boardKey = self.keyGenHelper.generateUniqueKey()
        var validData = false
        while(!validData){
        databaseRef?.child("events").queryOrdered(byChild: "key").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)
        })
        }

The problem here is that the while loop keeps going on and on and never got response from firebase. What would be the best approach for me to accomplish this task?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...