当应用程序处于后台模式或手机处于睡眠状态并且收到 VoIP 推送时,AppDelegate 中的以下函数会引导用户(到UserTableViewController
在应用程序中)并发布通知。
viewDidLoad 中的通知观察者UserTableViewController
观察通知并致电func simulateMyIncomingCallFromNotification
.
我注意到当我第二次发送 VoIP 推送时func simulateMyIncomingCallFromNotification
被调用两次,第三次,三次,依此类推。如何避免多次通话?
其他SO答案建议删除通知观察者,我什至在设置通知观察者之前就这样做了,正如您在下面的扩展中看到的那样,但这似乎并不能解决我的问题。
我该如何解决这个问题?
在应用程序委托中:
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)
}
在用户表视图控制器中
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)
}