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

26,967

Solution 1

  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");
    }
}];

Solution 2

Follow the step: 1. Import UserNotifications.framework and go to your AppDelegate class.

In .h

#import <UserNotifications/UserNotifications.h>
@interface AppDelegate : UIResponder          <UIApplicationDelegate,UNUserNotificationCenterDelegate>

@end
  1. Register for push :

    #define SYSTEM_VERSION_GRATERTHAN_OR_EQUALTO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending) 
    

Now add this in did finish launching :

-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
   [self registerForRemoteNotifications];
return YES;
}

 - (void)registerForRemoteNotifications {
  if(SYSTEM_VERSION_GRATERTHAN_OR_EQUALTO(@"10.0")){
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate = self;
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error){
         if(!error){
             [[UIApplication sharedApplication] registerForRemoteNotifications];
         }
     }];  
}
else {
    // Code for old versions
}
}
  1. Delegate methods for UserNotifications :

      //Called when a notification is delivered to a foreground app.
    
     -(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler{
    NSLog(@"User Info : %@",notification.request.content.userInfo);
    completionHandler(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge);
    }
    
     //Called to let your app know which action was selected by the user for a given notification.
     -(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler{
     NSLog(@"User Info : %@",response.notification.request.content.userInfo);
      completionHandler();
      }
    
  2. Push Notifications Entitlements : From project target’s Capabilities tab and add Push Notifications Entitlements. enter image description here

  3. Add push and mobile certificate properly. Hope this is everything you need!

For more info: http://ashishkakkad.com/2016/09/push-notifications-in-ios-10-objective-c/

Share:
26,967

Related videos on Youtube

Developer
Author by

Developer

I'm an iOS and OS X developer. I work with Xcode.

Updated on July 09, 2022

Comments

  • Developer
    Developer almost 2 years

    I'd like to schedule local notifications using iOS 10. I'd like to know how to do this. I've looked all around the web, but I keep finding clues only for registering and handeling the notifications. Not for the scheduling of a local notification.

    So, does anyone know how to do this?

    • Martin R
      Martin R over 7 years
      Did you read "Scheduling Local Notifications" in Apple's "Local and Remote Notification Programming Guide"?
  • Developer
    Developer over 7 years
    Okay, now the app is able to schedule the notifications. But how exactly do you schedule one?
  • Jamshed Alam
    Jamshed Alam over 7 years
    What do mean by scheduling ? Do you want to set a local notification for some consecutive day. right ? please.
  • Developer
    Developer over 7 years
    Yes, next week for example
  • Jamshed Alam
    Jamshed Alam over 7 years
    ok. wait a few min. let me implement it please.
  • Martin R
    Martin R over 7 years
    Your code is identical to the one given in stackoverflow.com/a/39894962/1187415. If you copy code from other resources, add a link to the source for proper attribution.
  • Jamshed Alam
    Jamshed Alam over 7 years
    I am helped from another source martin. Thanks anyways. @Martin R
  • Jamshed Alam
    Jamshed Alam over 7 years
    For testing, match with your local GMT time. You can test on simulator.
  • Akshatha S R
    Akshatha S R over 7 years
    Can you post the complete code? I'm not getting the alarm..
  • Hanz Cheah
    Hanz Cheah almost 6 years
    The sample is not working, the notification box doesn't appear anywhere even i sent the date to now? if there some missing code?
  • Jamshed Alam
    Jamshed Alam almost 6 years
    After setting notification , do you get your array of all notification ? Please log it. @HanzCheah
  • rickrvo
    rickrvo over 5 years
    could you share the other source @JamshedAlam ?