How can I make UNNotificationRequest pop immediately?
Asked Answered
C

2

11

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)
}
Cornelia answered 26/4, 2017 at 14:26 Comment(2)
You have to implement some methods...see hereNeptune
Thank you the problem is solved :)Cornelia
B
18

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)
Bonner answered 8/4, 2019 at 16:34 Comment(4)
trigger:nil works for me. Tested IOS 12.2, Iphone 6S Plus.Axes
Worked for me on iOS13.Lacrimator
Somehow, I'm seeing about a five second delay before the notification shows up when doing this and haven't figured out what it could be.Floss
post this as a separate question and I will try to research what might be causing this @FlossBonner
S
-1

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?

Suppuration answered 26/4, 2017 at 14:34 Comment(1)
This is for a test I want just to show notification when I click on the button.Cornelia

© 2022 - 2024 — McMap. All rights reserved.