在一定时间后隐藏NSUserNotification

KD.*_*KD. 5 cocoa notifications swift2

目前,当我使用Alert样式创建NSUserNotification时,除非我手动将其关闭,否则它不会隐藏。

在此处输入图片说明

有没有一种方法可以让我在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)
Run Code Online (Sandbox Code Playgroud)

Elm*_*Cat 5

使用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))
Run Code Online (Sandbox Code Playgroud)