Swift 如何在Firestore集合中按时间戳订购?
我试图按时间戳排序,字段名为'Alpha',但遇到了一个错误:“在展开可选值时意外地发现了nil”。我已经试着按照文档进行操作,但仍然不太确定哪里出了问题。任何帮助都将不胜感激 我在下面详述我的代码:Swift 如何在Firestore集合中按时间戳订购?,swift,firebase,google-cloud-firestore,Swift,Firebase,Google Cloud Firestore,我试图按时间戳排序,字段名为'Alpha',但遇到了一个错误:“在展开可选值时意外地发现了nil”。我已经试着按照文档进行操作,但仍然不太确定哪里出了问题。任何帮助都将不胜感激 我在下面详述我的代码: func getFollowingPosts() { db.collection("iAmFollowing").document(currentUserID!).getDocument { (document, error) in
func getFollowingPosts() {
db.collection("iAmFollowing").document(currentUserID!).getDocument { (document, error) in
if error != nil {
print("ERROR")
} else {
if let document = document, document.exists {
let followedUID = document.get("uid") as? String
self.db.collection("posts")
.order(by: "Alpha")
.whereField("uid", isEqualTo: followedUID!).getDocuments(completion: { (documents, error) in
for documents in documents!.documents {
let title = documents.get("Title") as! String
let content = documents.get("Content") as! String
let username = documents.get("username") as! String
let postID = documents.get("postID")
let counter = documents.get("counter")
self.titleArray.append(title)
self.contentArray.append(content)
self.usernameArray.append(username)
self.postIDArray.append(postID as! Int)
self.effectsLabelArray.append(counter as! Int)
print(self.titleArray)
self.tableView.reloadData()
}
}
)}
}
}
}
多亏了Kiril S,这个问题已经解决了。我需要安全地打开包装
...
self.db.collection("posts")
.order(by: "Alpha")
.whereField("uid", isEqualTo: followedUID!).getDocuments(completion: { (documents, error) in
guard let documents = documents else {
print("NO DOCUMENTS")
return
}
for documents in documents!.documents {
let title = documents.get("Title") as! String
let content = documents.get("Content") as! String
let username = documents.get("username") as! String
let postID = documents.get("postID")
let counter = documents.get("counter")
self.titleArray.append(title)
self.contentArray.append(content)
self.usernameArray.append(username)
self.postIDArray.append(postID as! Int)
self.effectsLabelArray.append(counter as! Int)
print(self.titleArray)
self.tableView.reloadData()
}
}
...
然后,控制台提示我创建一个复合索引。在此之后,我可以同时使用.whereField和.orderBy。错误来自哪一行?我看到1-您正在强制展开一些可能为零的字段(
as!String
)。相反,可以使用可选值(as?String
)展开,也可以使用guard展开,如果您想跳过没有该字段的条目,并且您正在访问潜在后台线程上的UI元素,则应用程序将间歇性崩溃。在DispatchQueue.main.async
Hi中包装任何UI访问-谢谢。我马上试试这个。错误来自“for documents in documents!.documents”行,您也不应该强制展开该行!相反:guard let documents=ducuments else{/*您的查询没有返回任何文档,没有要循环的内容*/return}
,然后对文档中的文档执行。
这无疑消除了错误,但它没有对数据进行排序。你知道为什么它实际上没有从数据库返回任何数据吗?我认为。whereField
应该在订单之前。您可以逐个调试您的条件:首先,禁用/删除.whereField
条件,查看单独排序是否返回数据。然后分别测试.whereField
。