观察者使用removeAllObervers触发多次

时间:2016-07-25 18:10:15

标签: ios swift firebase firebase-realtime-database

我有一个IBAction,当按下它时,它会创建一个观察者监听器并获取快照数据。

当某个子节点更改值时,我想关闭当前的ViewController并呈现不同的ViewController。

当ViewController被解雇时,我试图删除所有观察者句柄。

但是当我构建并运行时,从我的控制台输出判断,似乎我的Firebase Observer被多次调用而未知。

This is being executed in the observer
This is being executed in the observer
This is being executed in the observer
This is being executed in the observer
This is being executed in the observer
This is being executed in the observer
2016-07-25 14:03:06.125 SSM[636:140771] Warning: Attempt to present <SSM.activeViewController: 0x13eb3b200> on <SSM.userProfileViewController: 0x13f18c400> while a presentation is in progress!
2016-07-25 14:03:06.125 SSM[636:140771] Warning: Attempt to dismiss from view controller <UINavigationController: 0x13f24ba00> while a presentation or dismiss is in progress!
2016-07-25 14:03:06.125 SSM[636:140771] Warning: Attempt to present <SSM.activeViewController: 0x13eb3b200> on <SSM.userProfileViewController: 0x13f18c400> while a presentation is in progress!
2016-07-25 14:03:06.125 SSM[636:140771] Warning: Attempt to dismiss from view controller <UINavigationController: 0x13f24ba00> while a presentation or dismiss is in progress!
2016-07-25 14:03:06.125 SSM[636:140771] Warning: Attempt to present <SSM.activeViewController: 0x13eb3b200> on <SSM.userProfileViewController: 0x13f18c400> while a presentation is in progress!
2016-07-25 14:03:06.125 SSM[636:140771] Warning: Attempt to dismiss from view controller <UINavigationController: 0x13f24ba00> while a presentation or dismiss is in progress!
来自IBAction的

片段

  self.rootRef.child("users/").child(NSUserDefaults.standardUserDefaults().stringForKey("id")!).observeEventType(.Value, withBlock: { snapshot in
        if (snapshot.value!.objectForKey("otherUserID") as? String)! != "" {

            print("This is being executed in the observer")

            self.dismissViewControllerAnimated(false, completion: nil)

            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            let controller = storyboard.instantiateViewControllerWithIdentifier("active")
            self.presentViewController(controller, animated: true, completion: nil)
        }
    })


override func viewDidDisappear(animated: Bool) {
    self.rootRef.child(NSUserDefaults.standardUserDefaults().stringForKey("id")!).removeAllObservers()
}

1 个答案:

答案 0 :(得分:4)

您可以使用observeSingleEventOfType(.Value, withBlock:,因此您不必删除观察者

另外,正如@Shubhank指出的那样,你必须在你被解雇的视图控制器中呈现VC。因为你已经解雇了自我,所以自我无效,这就是警告的原因