目前,当我使用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)发布于 2015-12-26 01:19:56
实际上,使用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))对于Swift 5,您可以使用以下方法:
let delayBeforeDelivering: TimeInterval = 10
let delayBeforeDismissing: TimeInterval = 2
let notification = NSUserNotification()
notification.title = "Title"
notification.deliveryDate = Date(timeIntervalSinceNow: delayBeforeDelivering)
let notificationcenter = NSUserNotificationCenter.default
notificationcenter.scheduleNotification(notification)
notificationcenter.perform(#selector(NSUserNotificationCenter.removeDeliveredNotification(_:)),
with: notification,
afterDelay: (delayBeforeDelivering + delayBeforeDismissing))发布于 2015-12-22 10:29:38
您可以在计时器中使用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及更高版本)
https://stackoverflow.com/questions/34408343
复制相似问题