当应用程序处于后台模式或手机处于睡眠状态并且收到VoIp推送时,AppDelagte中的以下功能会指示用户(应用中的UserTableViewController
)并发布通知。
UserTableViewController
的viewDidLoad中的通知观察者会观察通知并调用func simulateMyIncomingCallFromNotification
。
我注意到当我第二次发送VoIP推送时,func simulateMyIncomingCallFromNotification
被调用两次,第三次,三次,等等。如何避免多次通话?
其他SO答案,建议删除Notification观察者,我在设置之前就已经做了,正如您在下面的扩展中所看到的那样,但这似乎并没有解决我的问题。
我该如何解决这个问题?
在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)
}
答案 0 :(得分:2)
Apple建议观察员应在viewWillAppear
注册并在viewWillDissapear
中取消注册。
你能尝试这样吗。
答案 1 :(得分:2)
对通知进行多次调用可能是您的控制器未被初始化以及每次向该控制器的新实例添加新观察者时的情况。 你能做什么:
在该方法上添加断点并尝试 deinit() {
print(self)
}
并查看多次呼叫的地址。
或只是添加
System.getProperty()
并检查该课程是否被除名。
如果不是这样的话,你可以试试@ Himanth解决方案。
答案 2 :(得分:0)
在我的情况下,Notification
正在调用 次数 我出现在同一屏幕上并导致触发 相同的操作 X numberofTime 我进入屏幕。因此,我删除了 Notification
中的 viewWillDisappear
观察者,这实际上是有效的,并且在同一屏幕中停止了多次触发的操作/方法。 >
感谢 Himanth 的回答,我已经想通了
addObserver
override func viewDidLoad(){
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(self.yourNotificationAction(notification:)), name: Notification.Name("yourNotificationName"), object: nil)
}
<块引用>
removeObserver
屏幕消失时
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self, name: Notification.Name("yourNotificationName"), object: nil)
}