当应用程序在后台模式或手机处于睡眠状态且接收到VoIP推送时,AppDelagte中的以下函数将指示用户前往应用程序中的UserTableViewController,并发布通知。
在UserTableViewController的viewDidLoad中,通知观察器观察通知并调用simulateMyIncomingCallFromNotification函数。
我注意到当我第二次发送VoIP推送时,simulateMyIncomingCallFromNotification函数会被调用两次,第三次会调用三次,依此类推。如何避免多次调用?
其他SO答案建议删除通知观察器,但是我甚至在设置通知观察器之前就已经这样做了,如下所示的扩展,但似乎无法解决我的问题。
我该如何解决这个问题?
在AppDelegate中:
在UserTableViewController中
在UserTableViewController的viewDidLoad中,通知观察器观察通知并调用simulateMyIncomingCallFromNotification函数。
我注意到当我第二次发送VoIP推送时,simulateMyIncomingCallFromNotification函数会被调用两次,第三次会调用三次,依此类推。如何避免多次调用?
其他SO答案建议删除通知观察器,但是我甚至在设置通知观察器之前就已经这样做了,如下所示的扩展,但似乎无法解决我的问题。
我该如何解决这个问题?
在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)
}