iosswiftunusernotificationcenter

UNUserNotification doesn't fire out my local notification under iOS 12


In code I try to do it like this:

import UserNotifications

if #available(iOS 10.0, *) {
        let center = UNUserNotificationCenter.current()
        center.requestAuthorization(options: [.alert, .sound]) { _, _ in }
        let content = UNMutableNotificationContent()
        content.title = "Hello Staff"
        content.body = "Customer just ordered a milk with croissant"
        content.sound = UNNotificationSound.default()
        let date = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: Date(timeIntervalSinceNow: 10))
        let trigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: false)
        let request = UNNotificationRequest(identifier: "abcde", content: content, trigger: trigger)
        center.add(request)
}

All happens within AppDelegate. But I can't see any local notification. Why?


Solution

  • Your code is working fine. I guess the problem is that your app is active when you receive the notifications. iOS shows system notifications only if the app is not active. If app is active when notifications fires, the system triggers the UNUserNotificationCenterDelegate method so you could handle the notification by yourself.

    So since you set a notification time with a delay for 10 seconds, you need to run your app, then close it and wait for 10 seconds. Notification should appear if you give your app such a permission.