Uilocalnotification Is Deprecated in iOS 10

UILocalNotification is deprecated in iOS 10

Yes, you can use UILocalNotification, old APIs also works fine with iOS 10, but we had better use the APIs in the User Notifications framework instead. There are also some new features, you can only use with iOS 10 User Notifications framework.

This also happens to Remote Notification, for more information: Here.

New Features:

  • Now you can either present alert, sound or increase badge while the app is in foreground too with iOS 10
  • Now you can handle all event in one place when user tapped (or slided) the action button, even while the app has already been killed.
  • Support 3D touch instead of sliding gesture.
  • Now you can remove specific local notifications with just one line of code.
  • Support Rich Notification with custom UI.

It is really easy for us to convert UILocalNotification APIs to iOS 10
User Notifications framework APIs, they are really similar.

I wrote a demo here to show how to use new and old APIs at the same time: iOS 10 Adaptation Tips .

For example,

With Swift implementation:

  1. import UserNotifications

    ///    Notification become independent from UIKit
    import UserNotifications
  2. request authorization for localNotification

        let center = UNUserNotificationCenter.current()
    center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
    // Enable or disable features based on authorization.
    }
  3. schedule localNotification

  4. update application icon badge number

    @IBAction  func triggerNotification(){
    let content = UNMutableNotificationContent()
    content.title = NSString.localizedUserNotificationString(forKey: "Elon said:", arguments: nil)
    content.body = NSString.localizedUserNotificationString(forKey: "Hello Tom!Get up, let's play with Jerry!", arguments: nil)
    content.sound = UNNotificationSound.default()
    content.badge = UIApplication.shared().applicationIconBadgeNumber + 1;
    content.categoryIdentifier = "com.elonchan.localNotification"
    // Deliver the notification in 60 seconds.
    let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 60.0, repeats: true)
    let request = UNNotificationRequest.init(identifier: "FiveSecond", content: content, trigger: trigger)

    // Schedule the notification.
    let center = UNUserNotificationCenter.current()
    center.add(request)
    }

    @IBAction func stopNotification(_ sender: AnyObject) {
    let center = UNUserNotificationCenter.current()
    center.removeAllPendingNotificationRequests()
    // or you can remove specifical notification:
    // center.removePendingNotificationRequests(withIdentifiers: ["FiveSecond"])
    }

Objective-C implementation:

  1. import UserNotifications

    // Notifications are independent from UIKit
    #import <UserNotifications/UserNotifications.h>
  2. request authorization for localNotification

    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert)
    completionHandler:^(BOOL granted, NSError * _Nullable error) {
    if (!error) {
    NSLog(@"request authorization succeeded!");
    [self showAlert];
    }
    }];
  3. schedule localNotification

  4. update application icon badge number

    UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
    content.title = [NSString localizedUserNotificationStringForKey:@"Elon said:"
    arguments:nil];
    content.body = [NSString localizedUserNotificationStringForKey:@"Hello Tom!Get up, let's play with Jerry!"
    arguments:nil];
    content.sound = [UNNotificationSound defaultSound];

    // 4. update application icon badge number
    content.badge = [NSNumber numberWithInteger:([UIApplication sharedApplication].applicationIconBadgeNumber + 1)];
    // Deliver the notification in five seconds.
    UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger
    triggerWithTimeInterval:5.f
    repeats:NO];
    UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"FiveSecond"
    content:content
    trigger:trigger];
    /// 3. schedule localNotification
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
    if (!error) {
    NSLog(@"add NotificationRequest succeeded!");
    }
    }];

updated

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'time interval must be at least 60 if repeating'

let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 60, repeats: true)

UILocalNotification receiving function deprecated in iOS10 (Swift 3.0)

I think there is a misunderstanding with your case UILocalNotification is deprecated so far (as you already mentioned "UILocalNotification is deprecated in iOS10" in your question) and that's what are you asking about:

UILocalNotification receiving function deprecated in iOS10 (Swift 3.0)

But method: userNotificationCenter(_:didReceive:withCompletionHandler:) has nothing to do with UILocalNotification, instead, it is related to the UserNotifications Framework, which does supports iOS 10 -as mentioned in its documentation-:

Sample Image

So basically, you should go UserNotification instead of -deprecated- UILocalNotification, therefore:

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void)

should work as expected with iOS 10.

How to schedule a local notification in iOS 10 (objective-c)


  1. Try it. Its deprecated but working code. Use it for Before iOS 10.0 :

    //Get all previous noti..
    NSLog(@"scheduled notifications: --%@----", [[UIApplication sharedApplication] scheduledLocalNotifications]);

    NSDate *now = [NSDate date];
    now = [now dateByAddingTimeInterval:60*60*24*7]; //7 for 7th day of the week.
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

    [calendar setTimeZone:[NSTimeZone localTimeZone]];
    NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit|NSTimeZoneCalendarUnit fromDate:now];


    NSDate *SetAlarmAt = [calendar dateFromComponents:components];


    UILocalNotification *localNotification = [[UILocalNotification alloc] init];

    localNotification.fireDate = SetAlarmAt;


    NSLog(@"FIRE DATE --%@----",[SetAlarmAt description]);

    localNotification.alertBody =@"Alert";

    localNotification.alertAction = [NSString stringWithFormat:@"My test for Weekly alarm"];

    localNotification.userInfo = @{
    @"alarmID":[NSString stringWithFormat:@"123"],
    @"SOUND_TYPE":[NSString stringWithFormat:@"hello.mp3"]
    };

    localNotification.repeatInterval=0; //[NSCalendar currentCalendar];


    [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];

    1. For iOS 10.0 and later: Now try with UserNotifications framework: Add the framework, and import like #import . In Appdelegate Didfinishluanch method.

      UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
      [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert)
      completionHandler:^(BOOL granted, NSError * _Nullable error) {
      if (!error) {
      NSLog(@"request succeeded!");
      [self testAlrt];
      }
      }];

In your ibaction or method, write it and test:

 NSDate *now = [NSDate date];

// NSLog(@"NSDate--before:%@",now);

now = [now dateByAddingTimeInterval:60*60*24*7];

NSLog(@"NSDate:%@",now);

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

[calendar setTimeZone:[NSTimeZone localTimeZone]];

NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit|NSTimeZoneCalendarUnit fromDate:now];

NSDate *todaySehri = [calendar dateFromComponents:components]; //unused



UNMutableNotificationContent *objNotificationContent = [[UNMutableNotificationContent alloc] init];
objNotificationContent.title = [NSString localizedUserNotificationStringForKey:@"Notification!" arguments:nil];
objNotificationContent.body = [NSString localizedUserNotificationStringForKey:@"This is local notification message!"
arguments:nil];
objNotificationContent.sound = [UNNotificationSound defaultSound];

/// 4. update application icon badge number
objNotificationContent.badge = @([[UIApplication sharedApplication] applicationIconBadgeNumber] + 1);


UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:components repeats:NO];


UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"ten"
content:objNotificationContent trigger:trigger];
/// 3. schedule localNotification
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
if (!error) {
NSLog(@"Local Notification succeeded");
}
else {
NSLog(@"Local Notification failed");
}
}];

How to replace depreciated UILocalNotification and add UNNotificationAction in iOS 10

I haven't used notifications in iOS 10 yet, so I went ahead and figured it out as a learning experience for myself, now I can pass it on to you.

UILocalNotification is depreciated in iOS 10 and replaced by the UserNotifications framework.

In your AppDelegate get authorization from the user to show notifications and set up the centers delegate with UNUserNotificationCenterDelegate:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.

let center = UNUserNotificationCenter.current()
center.delegate = self
let options: UNAuthorizationOptions = [.alert, .sound];
center.requestAuthorization(options: options) {
(granted, error) in
if !granted {
print("Something went wrong")
}
}

return true
}

Present the notification to the user:

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
// Play sound and show alert to the user
completionHandler([.alert,.sound])
}

Handling the actions:

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

// Determine the user action
switch response.actionIdentifier {
case UNNotificationDismissActionIdentifier:
print("Dismiss Action")
case UNNotificationDefaultActionIdentifier:
print("Default")
case "foo":
print("foo")
case "bar":
print("bar")
default:
print("Unknown action")
}
completionHandler()
}

Do this wherever you want to setup all actions and categories for all notifications in your app. Because they're assigned to the center, not the notification itself:

func setupActions() {

//create first action
let foo = UNNotificationAction(
identifier: "foo",
title: "foo"
)

//create second action
let bar = UNNotificationAction(
identifier: "bar",
title: "bar",
options: [.destructive]
)

//put the two actions into a category and give it an identifier
let cat = UNNotificationCategory(
identifier: "cat",
actions: [foo, bar],
intentIdentifiers: []
)

//add the category to the notification center
UNUserNotificationCenter.current().setNotificationCategories([cat])
}

And finally creating the actual notification:

func setupNotification() {

let content = UNMutableNotificationContent()

content.title = "Hello!"
content.body = "A message"
content.sound = UNNotificationSound.default()

//make sure to assign the correct category identifier
content.categoryIdentifier = "cat"

// Deliver the notification in five seconds.
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let request = UNNotificationRequest(identifier: "hello", content: content, trigger: trigger)
let center = UNUserNotificationCenter.current()

center.add(request) { (error : Error?) in
if let theError = error {
print("theError \(theError)")
}
}
}

Be sure to import UserNotifications in each class utilizing these functions.

More info: User Notifications documentation.

UNNotificationRequest to send local notification daily at a specific time

You can use UNCalendarNotificationTrigger for creating a notification that fires repeatedly using UNUserNotificationCenter. You can do something like this. The trick is to only have the time component in the Trigger date.

        let center = UNUserNotificationCenter.current()

let content = UNMutableNotificationContent()
content.title = "Attention!"
content.body = "Your daily alert is ready for you!"
content.sound = UNNotificationSound.default

let identifier = "com.yourdomain.notificationIdentifier"

var triggerDate = DateComponents()
triggerDate.hour = 18
triggerDate.minute = 30
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: true)

let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)

center.add(request, withCompletionHandler: { (error) in
if let error = error {
// Something went wrong
print("Error : \(error.localizedDescription)")
} else {
// Something went right
print("Success")
}
})


Related Topics



Leave a reply



Submit