Swift Firebase observe .childAdded is reacting to existing items instead of new ones

谁都会走 提交于 2020-06-29 03:34:52

问题


I have a ref and I only want to listen when new items are added (it's in viewWillAppear below). When a new item is added newItemsButton appears. If nothing new is added to what already exists inside the db then the button should't appear.

The problem is as soon as the observer starts to observe, the newItemButton appears even though nothing new was added. What am I doing wrong?

db:

-posts
   -postId_1
   -postId_2
   -postId_3

code:

var startKey: String?
let postsRef = Database.database().reference().child("posts")
let postsObserverRef = Database.database().reference().child("posts")

override func viewDidLoad() {
    super.viewDidLoad()

    paginate()
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    listenForNewItems()
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    postsObserverRef.removeAllObservers()
}

func listenForNewItems() {

    postsObserverRef.observe(.childAdded) { (snapshot) in

        let postId = snapshot.key
        let isContained = self.dataSource.contains { $0.postId == postId }

        if !isContained {

            // show newItemsButton
        }
    }
}

func paginate() {

    if startKey == nil {

        postsRef.queryOrderedByKey().queryLimited(toLast: 20)
            .observeSingleEvent(of: .value, with: { (snapshot) in
            // fill datasource
        })

    } else {

        postsRef.queryOrderedByKey().queryEnding(atValue: startKey).queryLimited(toLast: 21)
            .observeSingleEvent(of: .value, with: { (snapshot) in
            // fill datasource
        })
    }
}

来源:https://stackoverflow.com/questions/62410591/swift-firebase-observe-childadded-is-reacting-to-existing-items-instead-of-new

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!