2015-12-22 66 views
4

目前,当我创建NSUserNotification使用警报样式它不会隐藏,除非我手动关闭它。在一定的时间后隐藏NSUserNotification

enter image description here

有没有办法可以自动关闭/隐藏2秒后说的?

NSUserNotification码参考:

let notification:NSUserNotification = NSUserNotification() 
notification.title = "Title" 
notification.subtitle = "Subtitle" 
notification.informativeText = "Informative text" 

notification.soundName = NSUserNotificationDefaultSoundName 

notification.deliveryDate = NSDate(timeIntervalSinceNow: 10) 
notification.hasActionButton = false 
let notificationcenter:NSUserNotificationCenter = NSUserNotificationCenter.defaultUserNotificationCenter() 
notificationcenter.scheduleNotification(notification) 

回答

4

实际上,使用NSObject的 performSelector:withObject:afterDelay:方法很简单。

由于您在特定时间间隔后安排通知传递,因此您需要在解散之前添加附加延迟,直到传递之前的最初延迟。在这里,我已经把它们写成了10秒前的常量,并在解雇前2秒写出来:

let delayBeforeDelivering: NSTimeInterval = 10 
let delayBeforeDismissing: NSTimeInterval = 2 

let notification = NSUserNotification() 
notification.title = "Title" 
notification.deliveryDate = NSDate(timeIntervalSinceNow: delayBeforeDelivering) 

let notificationcenter = NSUserNotificationCenter.defaultUserNotificationCenter() 

notificationcenter.scheduleNotification(notification) 

notificationcenter.performSelector("removeDeliveredNotification:", 
    withObject: notification, 
    afterDelay: (delayBeforeDelivering + delayBeforeDismissing)) 
+0

太棒了。谢谢。这工作完美.. –

+0

如果你想把它留在通知中心呢? (只需删除弹出窗口)有没有办法做到这一点? –

0

块引用是否有办法可以自动关闭/隐藏2秒后说的?

不,您没有任何此类选项,直到OSX 10.11,可能在未来的Apple可能提供。

有三种方式,用户可以自定义NSUserNotification也被称为低吼通知:

  1. 横幅
  2. 警报

你作为一个开发者在无法控制系统设置。这取决于用户启用或禁用并选择他喜欢的通知类型。

如果您想要向用户显示任何警报,您可以创建自己的警报窗口并将其显示在该角落。您可以设置一个计时器关闭,或者提供操作按钮以在需要时关闭计时器。

更新1: 可可提供NSWindow & NSPanel(HUD和正常面板)。您可以根据需要自定义窗口或面板。检查有多种选项可以帮助您按照您的要求进行组装。

如果你不能得到的,说你想要一个圆角,那么你需要自定义窗口/图等

+0

Hi Anoop,谢谢你的回复。您建议使用自定义警报窗口?你能建议我应该看看这个API吗?我正在研究新的MS Outlook 2016应用程序,它实施了一些类似于默认的警报,但不是默认警报。它也自动隐藏。所以可能会使用类似的方法 –

1

您可以使用removeDeliveredNotification:或removeAllDeliveredNotifications与计时器

// 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; 

OS X (10.8及更高版本)

+0

嗨Parag,谢谢你。所以我尝试使用这个,但不幸的是它不会工作。这是我在之前的代码后添加的代码。 让秒= 15.0 令延迟=秒*双(NSEC_PER_SEC)//每秒纳秒 让dispatchTime = dispatch_time(DISPATCH_TIME_NOW,Int64的(延迟)) dispatch_after(dispatchTime,dispatch_get_main_queue(),{ 变种测试= NSUserNotificationCenter .removeAllDeliveredNotifications(notificationcenter) print(test) }) –

相关问题