試着改變你的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: -爲了使後剛剛/ SAVING: -
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,
}
現在你需要的是這些類型的索引存儲在一個字典,然後隨機化數組元素: -
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是您的網絡線程中的連續線程),那麼您所需要的就是隨機化這些索引t那個特定時間,並且針對該特定索引詢問測試。但現在要激活應用程序中的刪除功能,您還需要修改保存功能,即每當將新節點保存到數據庫時,請確保您還在數據庫中追加了active_Indexes節點,指數。
PPS: -您還需要更新您的安全規則來處理不同的認證狀態。
**是**的問題「是否可以查詢數據庫,所以我得到的所有孩子,其中user_uid等於我提供的用戶uid?」 –
,我該怎麼做? @ EICaptainv2.0 –
你找到答案了嗎? – UmarZaii