Search code examples
iosswift3localnotificationunusernotificationcenterusernotifications

UNUserNotificationCenter Swift - local notification not firing in specific cases


I'm facing issue while using Local Notifications in application.

I'm scheduling local notification with custom content & custom action category. It's scheduling & firing in iOS 11, but not in iOS 10.

As per documentation, it should be working in iOS 10 as well.

Why is my code not working in such specific cases?

Code is below:

AppDelegate.swift

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    .......

    if #available(iOS 10.0, *) {
        UNUserNotificationCenter.current().delegate = self
    }
    .......

    return true
}

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

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    
    print("Local Notification :: ", response)
}

Code for Custom Actions

func configureNotificationCenter() {

    let actionRemindAgain = UNNotificationAction(identifier: NTConstants.LocalNotification.action.remindMeAgain, title: "Remind me Again!⏰", options: [.authenticationRequired])
    let actionViewDetails = UNNotificationAction(identifier: NTConstants.LocalNotification.action.viewDetails, title: "View Details!", options: [.foreground])
    let actionClose = UNNotificationAction(identifier: NTConstants.LocalNotification.action.dismiss, title: "Dismiss", options: [])
    
    //Event Category
    let eventCategory = UNNotificationCategory(identifier: NTConstants.LocalNotification.category.reminder, actions: [actionRemindAgain, actionViewDetails, actionClose], intentIdentifiers: [], options: [])
    
    //Register Category
    UNUserNotificationCenter.current().setNotificationCategories([eventCategory])
}

Schedule Code

func scheduleLocalNotification() {
    
    self.configureNotificationCenter()
    
    //Local Notification
    let content = UNMutableNotificationContent()
    content.title = notifyTitle
    content.subtitle = notifySubTitle
    content.body = notifyDesc
    
    //Category
    content.categoryIdentifier = "reminder"
    
    //Trigger
    let scheduleDate = Date(timeIntervalSince1970: TimeInterval(scheduleTimeInterval / 1000)) //My Schedule Data
    let triggerDate = Calendar.current.date(byAdding: .hour, value: -2, to: scheduleDate) // Should be call before 2 hours
    let dateComponents = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute], from: triggerDate!)
    
    let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)
    
    //Request
    let request = UNNotificationRequest(identifier: "notification_\((notifyId))", content: content, trigger: trigger)
    
    //Add Request
    UNUserNotificationCenter.current().add(request) { (error) in
        if let error = error {
            NTPrint("Unable to add notification : \(error.localizedDescription)")
        }
        else {
            NTPrint("Scheduled :: ", request.identifier)
        }
    }
}

This code successfully works & schedules local notification. And resulting as below:

<UNNotificationRequest: 0x18d65360; 

identifier: notification_111, 

content: <UNNotificationContent: 0x18daead0; 

    title: Event..!!, 
    subtitle: 31 Mar at 2:00 PM to 01 Apr at 12:00 PM, 
    body: , 
    categoryIdentifier: reminder, 
    launchImageName: , 
    peopleIdentifiers: (), 
    threadIdentifier: , 
    attachments: (), 
    badge: (null), 
    sound: (null), 
    hasDefaultAction: YES, 
    defaultActionTitle: (null), 
    shouldAddToNotificationsList: YES, 
    shouldAlwaysAlertWhileAppIsForeground: NO, 
    shouldLockDevice: NO, 
    shouldPauseMedia: NO, 
    isSnoozeable: NO, 
    fromSnooze: NO, 
    darwinNotificationName: (null), 
    darwinSnoozedNotificationName: (null), 

    trigger: <UNCalendarNotificationTrigger: 0x18d51470; 
        dateComponents: <NSDateComponents: 0x18da3320>
        Calendar Year: 2018
        Month: 3
        Leap month: no
        Day: 31
        Hour: 12
        Minute: 00, 
    repeats: NO
>>

It's setting properly on 12 PM as I set before 2 hours. It's working fine in iOS 11 devices. But not working in iOS 10. Anything wrong with updated code? Or anything else need to be handled?


Solution

  • To generate local Notification, Content.body must not be null or blank.

    In case while parsing blank to body, iOS 10 will not generate local push. But it's working in iOS 11.

    Value of Content.body was the key issue.