Search code examples
iphoneswift3ios9ios10uilocalnotification

UILocalNotification in iOS 9 and UNMutableNotificationContent in iOS 10?


I need to give backward compatibility (iOS 9) to a project. I came up with this:

if #available(iOS 10.0, *) {
        let content = UNMutableNotificationContent()
    } else {
        // Fallback on earlier versions
    }

What should I write in Fallback? Do I need to create a local notification instance?


Solution

  • Here is a small example on supporting both version:

    Objective-c version:

    if #available(iOS 10.0, *) {
        UNMutableNotificationContent *objNotificationContent = [[UNMutableNotificationContent alloc] init];
        objNotificationContent.body = @"Notifications";
        objNotificationContent.badge = @([[UIApplication sharedApplication] applicationIconBadgeNumber] + 1);
        UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:60 repeats:NO];
        UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"identifier" content:objNotificationContent trigger:trigger];
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
            if (!error) {
            }
            else {
            }
        }];
    }
    else
    {
        UILocalNotification *localNotif = [[UILocalNotification alloc] init];
        localNotif.fireDate = [[NSDate date] dateByAddingTimeIntervalInterval:60];
        localNotif.alertBody = @"Notifications";
        localNotif.repeatInterval = NSCalendarUnitMinute;
        localNotif.applicationIconBadgeNumber = 0;
        [[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
    }
    

    Swift version:

    if #available(iOS 10.0, *) {
        let content = UNMutableNotificationContent()
        content.categoryIdentifier = "awesomeNotification"
        content.title = "Notification"
        content.body = "Body"
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: false)
        let request = UNNotificationRequest(identifier: "FiveSecond", content: content, trigger: trigger)
        let center = UNUserNotificationCenter.current()
        center.add(request) { (error) in
        }
    }
    else
    {
        let notification = UILocalNotification()
        notification.alertBody = "Notification"
        notification.fireDate = NSDate(timeIntervalSinceNow:60)
        notification.repeatInterval = NSCalendarUnit.Minute
        UIApplication.sharedApplication().cancelAllLocalNotifications()
        UIApplication.sharedApplication().scheduledLocalNotifications = [notification]
    }