[英]Mac OS X NSUserNotificationCenter notification get dismiss event/callback
虽然另一个(关闭)按钮显然是要关闭通知,但无论其自定义标题指示什么,当用户通过单击关闭按钮解除通知时,没有优雅的方式来获得通知。
但是,您可以执行的操作是监视默认用户通知中心的deliverNotifications属性:只要通知尚未解除,阵列就会包含通知。 通知被取消后,阵列将不再包含它。
这可以在NSUserNotificationCenter委托方法中实现,如下所示:
- (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];
});
});
}
此代码将检查通知是否仍然每200毫秒。 一旦它消失,将在主线程上调用-notificationHandler:方法,这只是一个任意的回调方法。
在此自定义-notificationHandler:方法中,您可以检查是否已为通知调用NSUserNotificationCenter的didActivateNotification:委托方法。 如果没有,用户很可能点击了通知的关闭按钮。
然而,这不是故障保护,因为用户也可能已经解除了通知,即没有点击关闭按钮。
在Swift 3中
func userNotificationCenter(_ center: NSUserNotificationCenter, didDismissAlert notification: NSUserNotification) {
print("dismissed")
}
这不是NSUserNotificationDelegate
一部分,但效果很好
在Swift 2.3中:
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
也会触发解雇回调
这帮助了我
func 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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.