即使观察者被移除,通知观察者也会被多次调用 [英] Notification observer called multiple times even though the observer is removed

查看:40
本文介绍了即使观察者被移除,通知观察者也会被多次调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当应用程序处于后台模式或手机处于睡眠状态并且接收到 VoIP 推送时,AppDelagte 中的以下函数会引导用户(到应用程序中的 UserTableViewController)并发布通知.

When the app is in background mode or phone is in sleep state and a VoIp push is received the below function in AppDelagte directs the user (to the UserTableViewController in the app) and posts a notification.

UserTableViewController 的 viewDidLoad 中的通知观察者观察通知并调用 funcsimulateMyIncomingCallFromNotification.

A notification observer in viewDidLoad of the UserTableViewController observes the notification and calls the func simulateMyIncomingCallFromNotification.

我注意到当我第二次发送 VoIP 推送时,func simulationMyIncomingCallFromNotification 被调用两次,第三次,三次,依此类推.如何避免多次调用?

I noticed that when I send a VoIP push the second time the func simulateMyIncomingCallFromNotification is called twice and on the third time, thrice and so on. How can I avoid multiple calls ?

其他 SO 答案,建议删除通知观察者,我什至在设置之前就已经这样做了,正如您在下面的扩展中看到的那样,但这似乎并没有解决我的问题.

Other SO answers, advised to remove the Notification observer, which I am doing even before setting one, as you can seen in the below extension, but this doesn't seem to solve my problem.

我该如何解决这个问题?

How could I resolve this issue ?

在 AppDelegate 中:

func pushRegistry(_ registry: PKPushRegistry, didReceiveIncomingPushWith payload: PKPushPayload, forType type: PKPushType) {

 let storyboard = UIStoryboard(name: "User", bundle: nil)

 VC = storyboard.instantiateViewController(withIdentifier: "UserTableViewController") as! UserTableViewController

 self.window = UIWindow(frame: UIScreen.main.bounds)
        self.window?.rootViewController = VC
        self.window?.makeKeyAndVisible()


NotificationCenter.default.post(name: Notification.Name("didReceiveIncomingVoipPush"), object: nil, userInfo: payloadDict)
}

在 UserTableViewController

extension NotificationCenter {
    func setObserver(_ observer: AnyObject, selector: Selector, name: NSNotification.Name, object: AnyObject?) {
        print("NotificationCenter.default before: \(NotificationCenter.default)")
        NotificationCenter.default.removeObserver(observer, name: name, object: object)
        NotificationCenter.default.addObserver(observer, selector: selector, name: name, object: object)
        print("NotificationCenter.default after: \(NotificationCenter.default)")
    }
}

fun viewDidLoad(){

NotificationCenter.default.setObserver(self, selector: #selector(self.simulateMyIncomingCallFromNotification(notification:)), name: Notification.Name("didReceiveIncomingVoipPush"), object: nil)

}

推荐答案

Apple 建议观察者应该在 viewWillAppear 中注册,在 viewWillDissapear 中取消注册.

Apple recommends that observers should be registered in viewWillAppear and unregistered in viewWillDissapear.

你能不能试试这个.

这篇关于即使观察者被移除,通知观察者也会被多次调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆