我試圖從swift中的firebase中獲取關係數據並將其存儲在數組中。它按所需方式獲取所有內容,但無法訪問最終數組。 我嘗試了一切我在網上找到,但不能使其正常工作。在從Swift中的Firebase中獲取後訪問最終陣列
有3個子節點我正在讀取,所以每次讀取它都將它追加到數組中。
輸出是:
success
success
success
我只是想讓它打印 「成功」 一次。
這裏是我的代碼:
// Here the child with the relations is loaded
func fetchFollowingSection1IDs() {
guard let userID = FIRAuth.auth()?.currentUser?.uid else { return }
let reference = FIRDatabase.database().reference().child("interests").child("relations").child("userAndSection1").child(userID)
reference.observe(.childAdded, with: { (snapshot) in
// It's supposed to fetch the details of Section1 according to the childs from the relations (they are the IDs of Section1)
self.fetchSection1(section1ID: snapshot.key, completionHandler: { success in
guard success == true else {
return
}
print("success")
self.collectionView?.reloadData()
})
}, withCancel: nil)
}
// Here it gets the details from Firebase
func fetchSection1(section1ID: String, completionHandler: @escaping (Bool) ->()) {
let ref = FIRDatabase.database().reference().child("interests").child("details").child("country").child("section1").child(section1ID)
ref.observeSingleEvent(of: .value, with: { (snapshot) in
self.collectionView?.refreshControl?.endRefreshing()
if let dictionary = snapshot.value as? [String: AnyObject] {
let section1 = Section1New(section1ID: section1ID, dictionary: dictionary)
self.section1s.append(section1)
}
completionHandler(true)
}) { (err) in
print("Failed to fetch section1s:", err)
}
}
我的火力地堡結構的關係是這樣的:
"interests" : {
"relations" : {
"userAndSection1" : {
"7fQvYMAO4yeVbb5gq1kEPTdR3XI3" : { // this is the user ID
"-KjS8r7Pbf6V2f0D1V9r" : true, // these are the IDs for Section1
"-KjS8tQdJbnZ7cXsNPm3" : true,
"-KjS8unhAoqOcfJB2IXh" : true
},
}
一切正確加載,並填充我收集的意見。由於三次附加到數組,所以它只是Section1的錯誤數量。
謝謝你的回答!
謝謝!我發現問題的解決方案後,這是不正確的代碼,我的需要!儘管如此,它可以幫助有類似問題的人:) –