NSUserNotificationCenter delegate not work when the app is not focus

1.5k Views Asked by At

I have the code like this.

[[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification:notification];
[[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate:self];

Also, I implement userNotificationCenter:shouldPresentNotification:. It works fine. However. when the app's window is not focused, this delegate method is not called, and the notification always present.

Any help?

1

There are 1 best solutions below

1
On BEST ANSWER

First, you should set the delegate before you send the -deliverNotification: message. If you don’t, it’s possible that your delegate method won’t be triggered even when it’s supposed to be.

Second, in the documentation for -userNotificationCenter:shouldPresentNotification:, it states:

userNotificationCenter:shouldPresentNotification:

Sent to the delegate when the user notification center has decided not to present your notification.

i.e. you will only see this method invoked when NSUserNotificationCenter has already decided not to show your notification. If it has decided that it should show it, it won’t bother asking.