Currently when i create a NSUserNotification using Alert style it won't hide unless i manually close it.
Is there a way i can auto close/hide it say after 2 sec?
NSUserNotification code is for reference :
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)
It's actually very simple to do this, using NSObject's
performSelector:withObject:afterDelay:
method.
Because you're scheduling the notification delivery after a certain time interval, you need to add the additional delay before dismissing, to the initial delay before delivering. Here, I've written them out as constants of 10 seconds before delivery, and 2 seconds before dismissal:
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))
And for Swift 5 you can use the following:
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))
You can use removeDeliveredNotification
: or removeAllDeliveredNotifications
with timer
// 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 and later)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With