gpt4 book ai didi

ios - 如何使用 Swift 代码检索快照计数

转载 作者:行者123 更新时间:2023-11-29 05:26:54 25 4
gpt4 key购买 nike

我是 swift 新手,正在开发我的第一个应用程序。在我的应用程序中,有一个我想在其上显示图像的 Collection View 。这些图像是从 Firebase 数据库检索的。

Firebase数据库的结构如下

{
"CHILD1" : {
"URL1" : "https://Child1_url1.com",
"URL2" : "https://Child1_url2.com",
"URL3" : "https://Child1_url3.com"
}
"CHILD2" : {
"URL1" : "https://Child2_url1.com",
"URL2" : "https://Child2_url2.com",
}
"CHILD3" : {
"URL1" : "https://Child3_url1.com",

}

}

为了检索网址,我使用下面的代码

override func viewDidLoad() {
super.viewDidLoad()
checkSectionCount()
}

func checkSectionCount(){
Database.database().reference().observe(.value) { (snapShot: DataSnapshot) in

let snapDict = snapShot.value as? NSDictionary
let snapCnt = String(snapDict!.count)
print("snapCnt --> \(snapCnt)")// This prints the number of child counts correctly

}
}

func numberOfSections(in collectionView: UICollectionView) -> Int {
return snapCnt //I am unable to refer the snapCnt to set the number of section dynamically here

}

如上面代码所示,我无法从 func checkSectionCount 中引用 snapCnt。我还尝试将此值作为函数参数返回,但是 swift 无法识别

中的 snapCnt
Database.database().reference(){ Code

}

不确定我在这里缺少什么。如果有人能指导我如何根据 Firebase 数据库中提供的详细信息动态设置 Collection View 的部分和行号,我将不胜感激。

最佳答案

数据是从 Firebase 异步加载的,因为它可能需要一些时间才能从服务器返回。主代码不会阻塞您的代码(并使应用程序无响应),而是继续运行。然后,当代码从服务器返回时,将调用完成处理程序。

如果您更改代码并添加一些日志记录语句,最容易看到这一点:

print("Before starting to get data")
Database.database().reference().observe(.value) { (snapShot: DataSnapshot) in
print("Got data")
}
print("After starting to get data")

当您运行此代码时,它会打印:

Before starting to get data

After starting to get data

Got data

这可能不是您期望的顺序,尽管这是正常且有记录的行为。

因此,任何需要数据库数据的代码都必须位于完成处理程序内,或者从那里调用。

有关如何处理此问题的更多示例,请参阅:

关于ios - 如何使用 Swift 代码检索快照计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58072162/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com