【问题标题】:Firestore iOS - Ordering collection by field in documentFirestore iOS - 按文档中的字段排序集合
【发布时间】:2020-12-05 07:49:48
【问题描述】:

我有一个名为“homeList”的数组,它观察“CURRENT_USER_FRIENDS_REF”集合并将其放置在数组中。我怎样才能做到这一点,以便我可以通过文档快照中的“时间戳”字段对该数组进行排序。

homeList 数组函数

    var homeList = [User]()

    func addHomeObserver(_ update: @escaping () -> Void) {
        CURRENT_USER_FRIENDS_REF.getDocuments { snapshot, error in
            self.homeList.removeAll()
            
            guard error == nil else {
                #if DEBUG
                    print("Error retrieving collection")
                #endif
                return
            }
            
            let group = DispatchGroup()
            
            for document in snapshot!.documents {
                let whosfrom = document.get("fromId") as? String
                let id = document.documentID
                **let timestamp = document.get("timestamp") as? NSNumber**
                group.enter()
                self.getUser(id, completion: { (user) in
                    if whosfrom != self.CURRENT_USER_ID {
                        self.homeList.append(user)
                    }
                    group.leave()
                })
            }
            
            group.notify(queue: .main) {
                update()
            }
        }
    }

当前用户好友参考:

    var CURRENT_USER_FRIENDS_REF: CollectionReference {
        return CURRENT_USER_REF.collection("friends")
    }

谢谢。

【问题讨论】:

    标签: ios swift firebase google-cloud-firestore swift3


    【解决方案1】:

    您可以在集合引用上使用order(by 来获取结果。

    CURRENT_USER_FRIENDS_REF.order(by: "timestamp", descending: true).getDocuments { snapshot, error in
    
    }
    

    【讨论】:

      猜你喜欢
      • 2019-11-03
      • 2019-09-26
      • 1970-01-01
      • 1970-01-01
      • 2022-09-27
      • 2020-07-05
      • 1970-01-01
      • 2021-07-29
      • 2021-02-25
      相关资源
      最近更新 更多