Reputation: 151
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)
}
Upvotes: 11
Views: 6298
Reputation: 89559
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)
Upvotes: 19
Reputation: 4094
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?
Upvotes: -1