问题描述
我正在从 Firestore 获取数据,映射文档并使用 FirestoreDecoder 对每个文档进行解码。但是,解码文档会暂时冻结 UI。在后台线程上运行代码没有区别。如何防止 UI 在解码过程中冻结?
let collection = Firestore.firestore().collection("roll_groups")
collection.addSnapshotListener { (snapshot,error) in
if let error = error {
print("Error fetching roll groups: \(error.localizedDescription)")
} else if let snapshot = snapshot {
dispatchQueue.global(qos: .background).async {
let rollGroups = snapshot.documents.map { doc -> RollGroup? in
do {
let rollGroup = try FirestoreDecoder().decode(RollGroup.self,from: doc.data())
return rollGroup
} catch {
print("Error decoding roll groups: \(error)")
return nil
}
}
dispatchQueue.main.async {
completion(rollGroups)
}
}
}
}
解决方法
可能的解决方案
看这段代码似乎一切正常,我只是想确认您的方法的 completion
绝对是 @escaping: completion()
否则它可能会导致此问题
此外,可能值得将实际的数据库调用 (collection.addSnapshotListener)
包装在
DispatchQueue.global(qos: .background).async
只是看看这是否有所作为,理论上不应该,但仍然值得一试