Search code examples
iosswiftuilocalnotificationlocalnotification

UNUserNotificationCenterDelegate not called XCode Swift


UNUserNotificationCenterDelegate functions are not called when receiving local notifications in ios (swift). Also, I am unable to receive notifications in foreground.

Here is my AppDelegate class


    
    let notificationCenter = UNUserNotificationCenter.current()

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        DBManager.createEditableCopyOfDatabaseIfNeeded()
        notificationCenter.delegate = self
        let options: UNAuthorizationOptions = [.alert, .sound, .badge]
        notificationCenter.requestAuthorization(options: options) {
            (didAllow, error) in
            if !didAllow {
                print("User has declined notifications")
            }
        }
        return true
    }
}

App Delegate Extension for UNUserNotificationCenterDelegate


    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.alert, .sound])
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        print(response.notification.request.content.userInfo)
        completionHandler()
    }

    func scheduleNotification(_ body: String,_ date:Date) {
        let identifier = self.convertDateInMiliseconds(date: date)
        let content = UNMutableNotificationContent()
        content.title = "TEST APP"
        content.body = body
        content.sound = UNNotificationSound.default
        content.badge = 1
        content.categoryIdentifier = "\(identifier)1234"
        let triggerWeekly = Calendar.current.dateComponents([.weekday, .hour, .minute, .second,], from: date)
        let trigger = UNCalendarNotificationTrigger(dateMatching: triggerWeekly, repeats: true)

        let request = UNNotificationRequest(identifier: "\(identifier)", content: content, trigger: trigger)
        UNUserNotificationCenter.current().add(request) { (error) in
            if error == nil {
                print("TRUE")
            } else {
                print("FALSE")
                print(error?.localizedDescription ?? "ERROR")
            }
        }
        let snoozeAction = UNNotificationAction(identifier: "Snooze", title: "Snooze", options: [])
        let deleteAction = UNNotificationAction(identifier: "DeleteAction", title: "Delete", options: [.destructive])
        let category = UNNotificationCategory(identifier: "\(identifier)1234",
            actions: [snoozeAction, deleteAction],
            intentIdentifiers: [],
            options: [])

        notificationCenter.setNotificationCategories([category])
    }

    func convertDateInMiliseconds(date: Date) -> Int {
        let since1970 = date.timeIntervalSince1970
        return Int(since1970 * 1000)
    }

}

I am using iOS 14, swift 5.0 and xcode 11.5.
I am receiving notifications in background but not in foreground.

Thanks.


Solution

  • Try this one please

    func scheduleNotification(_ body: String,_ date:Date) {
        let identifier = self.convertDateInMiliseconds(date: date)
        let content = UNMutableNotificationContent()
        content.title = "TEST APP"
        content.body = body
        content.sound = UNNotificationSound.default
        content.badge = 1
        content.categoryIdentifier = "\(identifier)1234"
        let triggerWeekly = Calendar.current.dateComponents([.weekday, .hour, .minute, .second,], from: date)
        let trigger = UNCalendarNotificationTrigger(dateMatching: triggerWeekly, repeats: true)
    
        let center = UNUserNotificationCenter.current()
        center.delegate = self
    
        let request = UNNotificationRequest(identifier: "\(identifier)", content: content, trigger: trigger)
        UNUserNotificationCenter.current().add(request) { (error) in
            if error == nil {
                print("TRUE")
            } else {
                print("FALSE")
                print(error?.localizedDescription ?? "ERROR")
            }
        }
        let snoozeAction = UNNotificationAction(identifier: "Snooze", title: "Snooze", options: [])
        let deleteAction = UNNotificationAction(identifier: "DeleteAction", title: "Delete", options: [.destructive])
        let category = UNNotificationCategory(identifier: "\(identifier)1234",
            actions: [snoozeAction, deleteAction],
            intentIdentifiers: [],
            options: [])
    
        notificationCenter.setNotificationCategories([category])
    }