use*_*776 2 cocoa nsnotificationcenter ios swift swift3
当应用程序处于后台模式或手机处于睡眠状态并且接收到 VoIP 推送时,AppDelagte 中的以下功能会引导用户(到UserTableViewController应用程序中)并发布通知。
的 viewDidLoad 中的通知观察者UserTableViewController观察通知并调用func simulateMyIncomingCallFromNotification.
我注意到当我第二次发送 VoIP 推送时,它会func 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)
}
Run Code Online (Sandbox Code Playgroud)
在 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)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1936 次 |
| 最近记录: |