Firebase知道数据何时不再是查询的一部分?

时间:2017-07-14 18:56:36

标签: swift firebase-realtime-database

在我的Firebase数据库中,我有包含Unix时间的子节点,并且我按照当前时间之后的时间查询。我将每个符合该条件的孩子的数据放入UICollectionView。当前时间超过其中一个孩子的时间时,我希望孩子过期,并从UICollectionView中删除。目前,在我重新启动应用程序之前,它不会被删除。以下是一些代码:

// in viewDidLoad
self.events_query = Database.database().reference().child("events").queryOrdered(byChild: "end-time").queryStarting(atValue: Date().timeIntervalSince1970)

// in viewWillAppear
func observeAllEvents() {
    self.events_query.observe(.value, with: { (snapshot) in

        guard let eids_dict = snapshot.value as? [String : AnyObject] else { return }
        let eids = Array(eids_dict.keys)

        for eid in eids {
            print(eid)
        }

        Event.getAllEvents(with: eids, ref: self.events_query.ref, completion: { (events) in

            if let feed_datasource = self.datasource as? EventFeedDatasource {
                feed_datasource.events = events
            }

            DispatchQueue.main.async {
                self.collectionView?.reloadData()
            }
        })

    })
}

// in viewDidDisappear
self.events_query.removeAllObservers()

这里是函数getAllEvents

static func getAllEvents(with eids: [String], ref: DatabaseReference, completion: @escaping (_ events: [Event]) -> Void) {
    var events = [Event]()
    let dispatch_groups = [DispatchGroup(), DispatchGroup()]

    for eid in eids {
        dispatch_groups[0].enter()
        ref.child(eid).observeSingleEvent(of: .value, with: { (snapshot) in
            guard let dictionary = snapshot.value as? [String : AnyObject] else { return }
            dispatch_groups[1].enter()

            // I'm not including `load` because all it does is parse the snapshot
            Event.load(with: dictionary, completion: { (event) in
                events.append(event)
                dispatch_groups[1].leave()
            })
            dispatch_groups[0].leave()
        })
    }

    dispatch_groups[0].notify(queue: DispatchQueue.main) {
        dispatch_groups[1].notify(queue: DispatchQueue.main) {
            completion(events)
        }
    }
}

0 个答案:

没有答案