在我的应用程序中,会在特定时间提供本地生成的通知。通知按预期生成并显示。当应用程序打开时,通知徽章会更新以显示单个通知(再次,如预期),但是,当应用程序位于后台时,徽章不会更新。
//This code schedules a notification for 7 days before a date (action.date)
private func scheduleNotificationIfRequired() {
let sevenDaysBeforeActionDate = Calendar.current.date(byAdding: .day, value: -7, to: action.date)!
var triggerDateComponents = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute], from: sevenDaysBeforeActionDate)
triggerDateComponents.hour = 21
triggerDateComponents.minute = 51
let content = UNMutableNotificationContent()
content.title = "Upcoming Deadline"
content.body = "Action Required by: \(formattedDate(from: action.date))"
content.sound = UNNotificationSound.default
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDateComponents, repeats: false)
let identif = action.action + action.name
let request = UNNotificationRequest(identifier: identif, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request)
}
class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {
var viewRouter: ViewRouter?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
UNUserNotificationCenter.current().delegate = self
return true
}
// Handle notification when the app is in the foreground
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
// Increment the badge number on the app icon
let currentbadge = UIApplication.shared.applicationIconBadgeNumber
UIApplication.shared.applicationIconBadgeNumber = currentbadge + 1
completionHandler([.badge, .sound, .banner]) // Ensure notification banner is displayed
// If the notification is tapped while the app is in the foreground, handle it here
handleNotification(notification)
}
//This is the code that doesn’t work as expected. “here” is never printed to terminal
// Handle notification when the app is in the background or terminated
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
// Increment the badge number on the app icon
let currentbadge = UIApplication.shared.applicationIconBadgeNumber
UIApplication.shared.applicationIconBadgeNumber = currentbadge + 1
print(currentbadge)
print("here")
print(UIApplication.shared.applicationIconBadgeNumber)
completionHandler()
}
}```