如何使用Swift从Firebase数据库参考路径中删除Observer?

时间:2018-06-20 13:30:05

标签: swift firebase firebase-realtime-database observers

我按照下面的函数使用users单例类成功地在Firebase路径DataService上读取和侦听了数据更改。

Firebase参考:

REF_USERS = DB_BASE.child("users")

函数附加/监听路径和转义:

func getUsers(handler: @escaping (_ name: String, _ discoverable: Bool) -> ()){

   REF_USERS.observe(.value) { (snapshot) in
        guard let usersSnapshot = snapshot.children.allObjects as? [DataSnapshot] else { return }
        for user in usersSnapshot{
            let name = user.childSnapshot(forPath: "name").value as! String
            let discoverable = user.childSnapshot(forPath: "discoverable").value as! Bool

            handler (name, discoverable)
        }
    }

}

我正在DiscoverVC中使用上述功能,

DataService.run.getUsers { (name, discoverable) in
            print("name: \(name), discoverable: \(discoverable)")
        }

如何在DiscoverVC函数中从viewWillDisappear中删除观察者?

我知道我需要在DatabaseHandle调用中传递一个removeObserver,如何构建该句柄?

override func viewWillDisappear(_ animated: Bool) {

        DataService.run.REF_USERS.removeObserver(withHandle: <#T##UInt#>)
    }

1 个答案:

答案 0 :(得分:1)

根据Firebase documentation on detaching listeners

  

将回调块添加到引用时,将返回FIRDatabaseHandle。这些句柄可用于删除回调块。

所以在您的情况下:

handle = REF_USERS.observe(.value) { (snapshot) in
  ...
}

然后在您的viewWillDisappear中:

override func viewWillDisappear(_ animated: Bool) {
    DataService.run.REF_USERS.removeObserver(withHandle: handle)
}