简体   繁体   中英

How can I make UNNotificationRequest pop immediately?

I'm working with UNNotificationRequest and I want that the notification popup immediately when I click on the button. but in this case it appears when I quit the application. Here's my code

@IBAction func shortNotifBtn(_ sender: Any) {
    let center = UNUserNotificationCenter.current()
    let content = UNMutableNotificationContent()
    content.title = "Late wake up call"
    content.body = "The early bird catches the worm, but the second mouse gets the cheese."
    content.categoryIdentifier = "alarm"
    content.userInfo = ["customData": "fizzbuzz"]
    content.sound = UNNotificationSound.default()
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
    let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
    center.add(request)
}

Max's answer is for the deprecated UILocalNotification when the question is regarding the more modern UNNotificationRequest .

The correct answer is to pass nil along. According to the documentation for UNNotificationRequest 's requestWithIdentifier:content:trigger:

trigger

The condition that causes the notification to be delivered. Specify nil to deliver the notification right away.

So in your code:

let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: nil)

https://developer.apple.com/reference/uikit/uilocalnotification

If the app is foremost and visible when the system delivers the notification, the app delegate's application(_:didReceive:) is called to process the notification. Use the information in the provided UILocalNotification object to decide what action to take. The system does not display any alerts, badge the app's icon, or play any sounds when the app is already frontmost.

That's the normal behavior. Besides why do you need to trigger a local notification by tapping a button? Why not to implement the desired functionality when the button is tapped and not trough notification?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM