我在从Firebase集合中获取字符串并将其显示在集合视图中时遇到问题。
基本上,我相信firebase函数对于程序的执行速度不够快,所以我将其放入也不能够解决问题的DispatchGroup中
//arrays of names and descriptions
var names:[String] = []
var descriptions: [String] = []
这是firebase函数,用于从firebase检索名称和描述
func firebase()
{
//connection to firebase for the names and descriptions
let db = Firestore.firestore()
db.collection(test).getDocuments { (snapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
for document in snapshot!.documents {
let name = document.get("Name") as! String
let description = document.get("Description") as! String
//Add names and descriptions to the arrays
self.names.append(name)
self.descriptions.append(description)
}
for x in self.names{
print(x)
}
for y in self.descriptions{
print(y)
}
}
}
}
这里是ViewDidLoad函数:当我不尝试打印名称[0]
时,它可以完美工作override func viewDidLoad() {
super.viewDidLoad()
let myGroup = DispatchGroup()
myGroup.enter()
firebase()
// When your task completes
myGroup.leave()
myGroup.notify(queue: DispatchQueue.main) {
// do your remaining work
print(self.names[1])
self.setupBottomControls()
self.setupTopControls()
self.setupButton()
self.setupImages()
self.collectionView?.backgroundColor = .white
self.collectionView?.register(PageCell.self, forCellWithReuseIdentifier: "cellId")
self.collectionView?.isPagingEnabled = true
}
}
我不断收到错误:
Fatal error: Index out of range
您正在滥用DispatchGroup
。在这种情况下是不合适的。
只需添加完成处理程序
func firebase(completion: @escaping () -> Void)
{
//connection to firebase for the names and descriptions
let db = Firestore.firestore()
db.collection(test).getDocuments { (snapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
for document in snapshot!.documents {
let name = document.get("Name") as! String
let description = document.get("Description") as! String
//Add names and descriptions to the arrays
self.names.append(name)
self.descriptions.append(description)
}
for x in self.names{
print(x)
}
for y in self.descriptions{
print(y)
}
completion()
}
}
}
并使用它
override func viewDidLoad() {
super.viewDidLoad()
firebase() { [unowned self] in
DispatchQueue.main.async {
// do your remaining work
print(self.names[1])
self.setupBottomControls()
self.setupTopControls()
self.setupButton()
self.setupImages()
self.collectionView?.backgroundColor = .white
self.collectionView?.register(PageCell.self, forCellWithReuseIdentifier: "cellId")
self.collectionView?.isPagingEnabled = true
}
}
}