首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >一定时间后隐藏NSUserNotification

一定时间后隐藏NSUserNotification
EN

Stack Overflow用户
提问于 2015-12-22 04:16:19
回答 2查看 1.9K关注 0票数 6

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

有什么办法能让我在2秒后自动关闭/隐藏它吗?

NSUserNotification代码可供参考:

代码语言:javascript
复制
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)
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-12-26 01:19:56

实际上,使用NSObject的performSelector:withObject:afterDelay:方法可以很简单地做到这一点。

因为要在一定时间间隔后调度通知传递,所以需要在发送之前将附加的延迟添加到初始延迟中。在这里,我已经把它们写成了发送前10秒和解雇前2秒的常量:

代码语言:javascript
复制
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,您可以使用以下方法:

代码语言:javascript
复制
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))
票数 6
EN

Stack Overflow用户

发布于 2015-12-22 10:29:38

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

代码语言:javascript
复制
// 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及更高版本)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34408343

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档