- (void)userNotificationCenter:(NSUserNotificationCenter *)center didDeliverNotification:(NSUserNotification *)notification
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
^{
BOOL notificationStillPresent;
do {
notificationStillPresent = NO;
for (NSUserNotification *nox in [[NSUserNotificationCenter defaultUserNotificationCenter] deliveredNotifications]) {
if ([nox.identifier isEqualToString:notification.identifier]) notificationStillPresent = YES;
}
if (notificationStillPresent) [NSThread sleepForTimeInterval:0.20f];
} while (notificationStillPresent);
dispatch_async(dispatch_get_main_queue(), ^{
[self notificationHandlerForNotification:notification];
});
});
}
在Swift 3中
func userNotificationCenter(_ center: NSUserNotificationCenter, didDismissAlert notification: NSUserNotification) {
print("dismissed")
}
这不是 NSUserNotificationDelegate
的一部分,但可以完美地工作。
@objc
注释;否则Objective-C运行时将无法看到你的委托方法。 - Felix J. Acerofunc userNotificationCenter(_ center: NSUserNotificationCenter, didActivate notification: NSUserNotification) {
switch (notification.activationType) {
case .none:
print("none CLicked")
break
case .actionButtonClicked:
print("Additional Action Clicked")
break
case .contentsClicked:
print("contents CLicked")
break
case .replied:
print("replied Action Clicked")
break
case .additionalActionClicked:
print("Additional MENU Action Clicked")
break
}
func userNotificationCenter(center: NSUserNotificationCenter, didDeliverNotification notification: NSUserNotification) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
var notificationStillPresent: Bool
repeat {
notificationStillPresent = false
for nox in NSUserNotificationCenter.defaultUserNotificationCenter().deliveredNotifications {
if nox.identifier == notification.identifier {
notificationStillPresent = true
break
}
}
if notificationStillPresent {
let _ = NSThread.sleepForTimeInterval(0.20)
}
} while notificationStillPresent
dispatch_async(dispatch_get_main_queue()) {
self.notificationHandlerFor(notification)
}
}
}
PS:请注意,这是检测解除事件的方法,可能会在多种情况下触发。
otherButton
解除Clear All
按钮PS 2:如果您正在使用 deliveryRepeatInterval
,比如 1 分钟,则在 deliveredNotifications
数组中有多个通知,但只显示一个。解除应触发多个回调。
PS 3:点击 actionButton
也会触发解除回调。
if
语句,以检查当前的[[NSUserNotificationCenter defaultUserNotificationCenter] deliveredNotifications].count
是否大于显示通知之前的[[NSUserNotificationCenter defaultUserNotificationCenter] deliveredNotifications].count
。这样做效果很好。谢谢! - Daniel Storm