2015-12-22 63 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) }) –

相關問題