在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
每个密钥都由运行应用程序的设备在本地自动生成(DF2342和AB1232),但我想先在设备上生成密钥,然后检查密钥是否已存在于firebase数据库中。如果确实存在,请重新生成密钥并重试。这里是我用的代码:
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)
})
}
这里的问题是while循环一直在继续,并且从未得到firebase的响应。对我来说,完成这项任务的最佳方法是什么?
答案 0 :(得分:2)
由于您的应用程序要求您不能使用childByAutoId
,因此确保生成唯一ID的方法是在firebase中仅存储您生成的ID的附加表。例如:
def bricks(small,big,goal):
current_lenght = 0
current_value = 5
number_of_bricks = big
builder(current_lenght,current_value,number_of_bricks,goal)
current_value = 1
print("in bricks", current_lenght)
number_of_bricks = small
builder(current_lenght,current_value,number_of_bricks,goal)
if current_lenght == goal:
return True
else:
return False
def builder(current_lenght,current_value,number_of_bricks,goal):
use_count = 1
while (goal - current_lenght) >+ current_value and use_count <= number_of_bricks:
current_lenght += current_value
print("in while ",current_lenght)
print(current_lenght)
return current_lenght
然后,当您生成密钥时,您可以执行以下操作:
"keys": {
"DF2342": true,
"AB1232": true,
...
}
您还需要确保将新生成的密钥写入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)
})
。