尝试将您的 JSON 树更改为:-
Users:
- uid
- email
tests
- noOfTotalTest : 4 // Lets say 4
- id
- title
- user_uid
- index // Just index of the post
现在使用这个代码块:-
FIRDatabase.database().reference().child("tests/noOfTotalTest").observeSingleEvent(of: .value, with: {(Snap) in
let totalNoOfTest = Snap.value as! Int
print(totalNoOfTest)
let randNum = Int(arc4random_uniform(UInt32(totalNoOfTest))) + 1
print(randNum)
FIRDatabase.database().reference().child("tests").queryOrdered(byChild: "index").queryEqual(toValue: randNum).observeSingleEvent(of: .value, with: {(Snapshot) in
print(Snapshot.value!)
})
})
现在,每当您向数据库发布测试时,您都必须执行以下操作:-
- 查询数据库中的测试总数,noOfTotalTest
- 检索后将其增加 +1 并更新 noOfTotalTest 并将其与其他测试详细信息一起放入并设置到您的数据库中
- 这个过程还在继续......
PS:- 只是为了发帖/ 保存:-
FIRDatabase.database().reference().child("tests/noOfTotalTest").observeSingleEvent(of: .value, with: {(Snap) in
if Snap.exists(){
// This is not the first post
let totalNoOfTest = Snap.value as! Int
FIRDatabase.database().reference().child("tests").childByAutoId().setValue(["userID" : UID, "details" : Details, "index" : totalNoOfTest + 1])
FIRDatabase.database().reference().child("tests/noOfTotalTest").setValue(totalNoOfTest + 1)
} else {
// This is your first post
FIRDatabase.database().reference().child("tests").childByAutoId().setValue(["userID" : UID, "details" : Details, "index" : 1])
FIRDatabase.database().reference().child("tests/noOfTotalTest").setValue(1)
}
})
要扩展此功能以便您能够删除,您可以保存节点中需要随机化的活动索引。
为此将其添加到您的 JSON 树中:-
active_Indexes :{
12 : true,
09 : true,
198 : true,
11: true,
103 : true,
}
现在您需要将这些 INDEX 存储在字典中,然后随机化数组元素:-
var localIndexDirectory = [Int : Bool]
//Listen to any changes to the database, and update your local index directory accordingly
override func viewDidLoad() {
super.viewDidLoad()
FIRDatabase.database().reference().child("active_Index").observe(.childRemoved, with: {(Snap) in
print(Snap.value)
let keyToBeChanged = Int(Snap.key)!
self.localIndexDirectory.removeValue(forKey: keyToBeChanged)
print(self.localIndexDirectory)
})
FIRDatabase.database().reference().child("active_Index").observe(.childAdded, with: {(Snap) in
print(Snap)
let keyToBeChanged = Int(Snap.key)!
self.localIndexDirectory.updateValue(true, forKey: keyToBeChanged)
print(self.localIndexDirectory)
})
}
这将使您的目录更新您数据库中可用的索引(SINCE .observe 是您的网络线程中的一个连续线程),那么您只需要在特定时间随机化这些索引并查询该特定索引的测试。但是现在要在您的应用程序中激活删除功能,您还需要修改您的 保存 功能,即每当您将新节点保存到数据库时,请确保您还附加 active_Indexes 节点,具有该特定索引。
PPS:-您还需要更新您的安全规则以处理不同的身份验证状态。