在从Swift中的Firebase中获取后访问最终阵列
问题描述:
我试图从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的错误数量。
谢谢你的回答!
答
该代码正在做你正在告诉它做的事情。
您的firebase事件是.childAdded,因此它将一次遍历每个子节点。
它首先加载-KjS8r7Pbf6V2f0D1V9r并将其添加到section1s数组中 - 然后在数组中有一个项目。
然后它加载-KjS8tQdJbnZ7cXsNPm3并追加到数组中。数组中有两项和两行输出。等等
我们在你的问题的代码中没有看到的唯一的一行是实际打印数组,这可能是在你的collectionView委托方法。
根据您的使用情况,您可能希望使用.value读取所有内容,然后遍历该数据以填充dataSource数组。
谢谢!我发现问题的解决方案后,这是不正确的代码,我的需要!尽管如此,它可以帮助有类似问题的人:) –