19

我正在嘗試爲我的應用程序使用新的Mountain Lion NSUserNotificationCenter(實際上並不太難)。發佈通知,通過NSUserNotificationCenter關閉通知

NSUserNotification *userNotification = [[NSUserNotification alloc] init]; 
userNotification.title = @"Some title"; 
userNotification.informativeText = @"Some text"; 

[[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification:userNotification]; 

但是用得好好的,我要取消那些在屏幕上,一旦應用程序獲得焦點的所有通知。例如。就像新的Messages應用程序一樣。當在後臺收到新消息時,會顯示通知。當應用程序再次激活時,它們會自動消失並從屏幕和通知中心消失。

要複製這個,我已經註冊了一個方法到NSApplicationDidBecomeActiveNotification通知,它也被成功調用。在那裏我叫[NSUserNotificationCenter defaultUserNotificationCenter] removeAllDeliveredNotifications]

但是,這樣做的效果是,通知中心收集的通知將被刪除,同時仍顯示右上角顯示的相應「泡泡」。

迭代所有交付的通知並將它們各自移除它們具有完全相同的效果,因爲使用scheduleNotification而不是deliverNotification

我是唯一一個遇到這種情況的人,還是我缺少一些以編程方式忽略通知屏幕部分和通知中心部分?

+0

聽起來像你應該報告這是http://bugreport.apple.com上的錯誤。 –

+0

已經做到了。並不是說蘋果公司的任何人都會真正閱讀它們,但只是爲了完成。不知道我是否在這裏錯過了一些東西,儘管這是我的錯。 – BinaryBucks

+0

在什麼情況下你使用通知,你需要有'氣泡'嗎? –

回答

17

Messages應用程序可能使用私有的NSUserNotificationCenter _removeAllDisplayedNotifications_removeDisplayedNotification:方法。

您可以嘗試使用這些方法來測試這是否是您要查找的內容。只需添加這一類接口聲明的方法:

@interface NSUserNotificationCenter (Private) 
- (void)_removeAllDisplayedNotifications; 
- (void)_removeDisplayedNotification:(NSUserNotification *)notification; 
@end 

不幸的是,因爲這些無證方法,你可以不通過App Store分發的應用程序中使用它們。如果這確實是您正在尋找的內容,那麼您應該要求這些方法成爲公共API的一部分。

+0

使用這些私有方法確實可行,謝謝。我不知道爲什麼這些方法不是公共API tbh的一部分。我會爲它提交一個錯誤報告。 – BinaryBucks

3

由於10.9,下面的方法刪除任何顯示的通知:

// Clear a delivered notification from the notification center. If the 
// notification is not in the delivered list, nothing happens. 
- (void)removeDeliveredNotification:(NSUserNotification *)notification; 

// Clear all delivered notifications for this application from the 
// notification center. 
- (void)removeAllDeliveredNotifications; 

的行爲似乎因爲10.8有所改變,因爲任何顯示的通知也會被刪除時,這些方法稱爲(感謝@ 0xced爲澄清)。

+0

你確定它們是一樣的嗎? **顯示** vs **交付**。在10.8上,它們的實現不一樣。 (我沒有檢查過10.9) – 0xced

+0

至少我在10.9上執行了一個測試,調用'-removeAllDeliveredNotifications'刪除了當前顯示的任何通知。我想這不應該是10.9的行爲。編輯反映,謝謝。 –

1

removeDeliveredNotification正在爲我刪除顯示的通知(在10.11上),告誡是identifier上的通知必須設置。