2017-09-27 105 views
1

當應用處於後臺模式或手機處於睡眠狀態並且收到VoIp推送時,AppDelagte中的以下功能會指示用戶(至應用中的UserTableViewController)以及發佈通知。儘管觀察者被移除,通知觀察者多次呼叫

UserTableViewController的viewDidLoad中的通知觀察者觀察通知並調用func simulateMyIncomingCallFromNotification

我注意到,當我第二次撥打VoIP推送號碼func simulateMyIncomingCallFromNotification兩次,第三次,三次等。我怎樣才能避免多個電話?

其他的答案,建議刪除通知觀察者,我甚至在設置之前,我正在做的,你可以在下面的擴展中看到,但這似乎並沒有解決我的問題。

我該如何解決這個問題?

在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) 

} 

回答

1

Apple建議觀察員應在viewWillAppear註冊和未註冊viewWillDissapear

你可以這樣試試。

2

在通知中獲取多個呼叫可能是您的控制器未被取消初始化以及您每次向該控制器的新實例添加新觀察者時的情況。 你可以做什麼:

在該方法上添加斷點並嘗試print(self)並查看倍數調用的地址。

或只加

deinit() { 
    print(self) 
} 

,並檢查類是否被deinitilized與否。

如果不是這種情況,您可以嘗試@Himanth解決方案。

+0

'在該方法上添加斷點或deinit()方法? – user44776

+0

多次調用的方法simulateMyIncomingCallFromNotification – ankit