Mac OS X NSUserNotificationCenter notification get dismiss event/callback

前端 未结 4 1393
猫巷女王i
猫巷女王i 2020-12-31 06:39

In our app we are displaying Notification Center notifications in alert style.

Displaying notification works fine, as well as we get callback when user interacts wit

4条回答
  •  礼貌的吻别
    2020-12-31 07:09

    In Swift 2.3:

    func userNotificationCenter(center: NSUserNotificationCenter, didDeliverNotification notification: NSUserNotification) {
    
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { 
            var notificationStillPresent: Bool
            repeat {
                notificationStillPresent = false
                for nox in NSUserNotificationCenter.defaultUserNotificationCenter().deliveredNotifications {
                    if nox.identifier == notification.identifier {
                        notificationStillPresent = true
                        break
                    }
                }
    
                if notificationStillPresent {
                    let _ = NSThread.sleepForTimeInterval(0.20)
                }
            } while notificationStillPresent
    
            dispatch_async(dispatch_get_main_queue()) {
                self.notificationHandlerFor(notification)
            }
        }
    }
    

    PS: Please also notice that it is the way to detect the dismiss event, which can be triggered in several cases.

    1. Click the otherButton to dismiss
    2. Click the Clear All button in Notification Center

    PS 2: If you are using deliveryRepeatInterval, say 1 minute, there are multiple notifications in deliveredNotifications array, while only one is displayed. The dismissal shall trigger multiple callbacks.

    PS 3: Clicking actionButton will also trigger the dismissal callback

提交回复
热议问题