ios - 从 tableView 中的 Firestore 单元格读取数据后随机重新排序
问题描述
我正在开发根据 ID 打印已访问地点名称的应用程序。我将数据存储在几个名为“placesExploredByUsers/userID”的节点中,该节点存储有关用户之前访问过的地点 ID 的数据,节点“databaseOfPlaces”存储所有地点的 ID 以及附加信息(名称、位置、坐标等),所以它就像 SQL 中的外键一样工作。我所有的数据都存储在 Firebase 中。
但是,我在 Swift 的 tableView 中排序我的单元格时遇到了问题。我尝试了几个选项,这是我最后一次修改。问题是,每次我使用 tableView 来到 viewController 时,我的单元格都会随机重新排序。
这是功能,应该处理它。
谁能帮帮我吗?提前致谢
func getDataToTable(){
// setting the firebase reference
ref = Database.database().reference()
let userID = (Auth.auth().currentUser?.uid)!
// getting information about places that user has visited
Database.database().reference().child("placesExploredByUsers").child(userID).queryOrderedByValue().observeSingleEvent(of: .value) { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject]{
// creating array of all ID of places that user has visited
let idsOfAllPlaces = Array(dictionary.keys)
for id in idsOfAllPlaces {
// getting information about places from database of ID of all places that are in app
Database.database().reference().child("databaseOfPlaces").child(id).queryOrderedByValue().observeSingleEvent(of: .value) { (snapshot1) in
if let dictionary = snapshot1.value as? [String: AnyObject]{
// getting information about name
self.random = dictionary["name"]! as! String
// updating the table view
self.postData.append(self.random)
self.sortedList(array: self.postData)
}
}
}
}
}
}
解决方案
根据文档
默认情况下,查询按文档 ID 升序检索满足查询的所有文档。您可以使用 orderBy() 指定数据的排序顺序,并且可以使用 limit() 限制检索到的文档数量。注意:orderBy() 子句还过滤给定字段的存在。结果集将不包括不包含给定字段的文档。
所以使用order(by: "databaseOfPlaces")
func getDataToTable(){
// setting the firebase reference
ref = Database.database().reference()
let userID = (Auth.auth().currentUser?.uid)!
// getting information about places that user has visited
Database.database().reference().child("placesExploredByUsers").child(userID).order(by: "databaseOfPlaces").observeSingleEvent(of: .value) { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject]{
// creating array of all ID of places that user has visited
let idsOfAllPlaces = Array(dictionary.keys)
for id in idsOfAllPlaces {
// getting information about places from database of ID of all places that are in app
Database.database().reference().child("databaseOfPlaces").child(id).queryOrderedByValue().observeSingleEvent(of: .value) { (snapshot1) in
if let dictionary = snapshot1.value as? [String: AnyObject]{
// getting information about name
self.random = dictionary["name"]! as! String
// updating the table view
self.postData.append(self.random)
self.sortedList(array: self.postData)
}
}
}
}
}
}
推荐阅读
- java - 在函数 fromJson 之前向类注入一些属性
- java - dl4j -paragraph2vec 中的标签机制是什么?
- javascript - 如果通过 XHR 从客户端 JS 函数调用 Express,则不会在浏览器中呈现页面
- javascript - 在处理递归时,使用 Promises 的 reduce 模式的替代方案是什么?
- ant - 仪表 | 从 jtl 文件中获取样本的通过/失败计数
- mysql - 基于重复值更新字段
- c# - 如何在 .net 核心中记录自定义 ado.net SQL 查询?
- c - 后缀表达式(类型名称){initializer-list}
- hadoop - 如何使用 Hadoop api 判断文件是否为空?
- webgl - 有没有办法使用异步函数将数据(缓冲区数据)并行传递给 gpu?