6

I'm using UNUserNotificationCenter for ios 10. For testing, I'm setting a local notification for 10 seconds from current time.

This is what I tried,

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

-(void) set10Notifs
{
    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {
    #if XCODE_VERSION_GREATER_THAN_OR_EQUAL_TO_8
     NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

    [calendar setTimeZone:[NSTimeZone localTimeZone]];        

    NSDateComponents *components = [calendar components:NSCalendarUnitTimeZone fromDate:[[NSDate date] dateByAddingTimeInterval:10]];

    UNMutableNotificationContent *objNotificationContent = [[UNMutableNotificationContent alloc] init];
    objNotificationContent.title = [NSString localizedUserNotificationStringForKey:@"Prayer!" arguments:nil];
    objNotificationContent.body = [NSString localizedUserNotificationStringForKey:@"Time now"
                                                                        arguments:nil];
    objNotificationContent.sound = [UNNotificationSound defaultSound];

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


    UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"Prayer"
                                                                          content:objNotificationContent trigger:trigger];
    UNUserNotificationCenter *userCenter = [UNUserNotificationCenter currentNotificationCenter];
    [userCenter addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
        if (!error) {
            NSLog(@"Local Notification succeeded");
        }
        else {
            NSLog(@"Local Notification failed");
        }
    }];
#endif
    }
}

I can see the log "Local Notification succeeded". But the local notification is not firing in the device.

In Appdelegate, I added

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  // Override point for customization after application launch.
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate = self;
    return YES;
}
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
   willPresentNotification:(UNNotification *)notification
     withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {
    NSLog(@"Notification is triggered");
     completionHandler(UNNotificationPresentationOptionBadge);
} 

-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler{
    NSLog(@"User Info : %@",response.notification.request.content.userInfo);
    completionHandler();
}

What did I do wrong? Why the app notifications not fired?

Nazik
  • 8,696
  • 27
  • 77
  • 123
  • http://stackoverflow.com/questions/37807302/add-local-notification-in-ios10-swift-3?rq=1 – Sanju Oct 19 '16 at 07:03
  • check your device time and triggertime -- http://stackoverflow.com/questions/39941778/how-to-schedule-a-local-notification-in-ios-10-objective-c?rq=1 – Sanju Oct 19 '16 at 07:05
  • Have you enabled push notifications from Xcode settings? – Stefan Oct 19 '16 at 07:07
  • @Sanjuju, what should I check with device time? I gave 10 seconds addingInterval to Nsdate.... – Nazik Oct 19 '16 at 07:07
  • @Stefan, is it needed to enable Push notifications? I'm using just local notifications – Nazik Oct 19 '16 at 07:08
  • 1
    You've set the fire time as 10 seconds in the future. Are you putting the app to the background within 10 seconds of the notification being scheduled? If not, the notification will not pop-up on screen, it will be passed into your app delegate (where you have to handle it yourself). Put a breakpoint in your app delegate at `application:didReceiveLocalNotification:` to check. – norders Oct 19 '16 at 07:15
  • @norders, I added delegate methods in Appdelegate file. and I also put my app in background before 10 secs as well as quitting the app. notification not fired. Even I tried 20 seconds... – Nazik Oct 19 '16 at 07:28
  • For NSDateComponents, try: NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit|NSTimeZoneCalendarUnit fromDate:[[NSDate date] dateByAddingTimeInterval:10]]; – Jamshed Alam Oct 19 '16 at 10:21
  • @JamshedAlam, yes it's working... Thank u. You can post this as an answer to let me accept... – Nazik Oct 19 '16 at 10:27
  • You are most welcome. @NAZIK – Jamshed Alam Oct 19 '16 at 10:32

3 Answers3

9

Set NSDateComponents like:

NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond|NSCalendarUnitTimeZone fromDate:[[NSDate date] dateByAddingTimeInterval:10]];
Nate4436271
  • 860
  • 1
  • 10
  • 21
Jamshed Alam
  • 12,424
  • 5
  • 26
  • 49
  • Can't set [multiple notifications](http://stackoverflow.com/questions/40216915/multiple-unusernotifications-not-firing).... – Nazik Oct 24 '16 at 11:37
  • 1
    It appears you have to create the date components from the calendar's `dateComponents(_ components: Set, from date: Date)` function. Initializing the date components from any of the other calendar `dateComponents...` functions seems to not schedule the notification. (Swift 3) – LOP_Luke Jan 30 '17 at 16:36
  • @NAZIK, how did you make worked it for multiple notification ? i am stuck on same issue. Please have a look: https://stackoverflow.com/questions/44132879/ios-local-notification-not-firing-second-time-but-shows-in-getpendingnotificatio – Jamshed Alam Jun 04 '17 at 06:03
  • Thanks, dude. Looked everywhere and only this solution worked. – Quaggie Jan 16 '18 at 16:25
  • OMG @LOP_Luke, I spent ages trying to work out why my otherwise perfect looking notifications weren't being scheduled, and this answer and your comment solved it! I was using the wrong `dateComponents` function. Who knew there was such a thing. Thanks. – Rob Glassey Aug 25 '18 at 18:16
0

Or use a time trigger instead of a calendar trigger

Jerry
  • 4,382
  • 2
  • 35
  • 29
-1
@IBAction func sendNotification(_ sender: Any) {

    let content = UNMutableNotificationContent()
    content.title = "Hello"
    content.body = "Ved Rauniyar !!!"
   // content.badge = 1
    content.sound = UNNotificationSound.default()
    // Deliver the notification in five seconds.
    let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 5, repeats: false)
    let url = Bundle.main.url(forResource:"ved", withExtension: "png")
    let attachment = try? UNNotificationAttachment(identifier: "FiveSecond",
                                                   url: url!,
                                                   options: [:])
    content.attachments = [attachment!]
    let request = UNNotificationRequest.init(identifier: "FiveSecond", content: content, trigger: trigger)
    // Schedule the notification.
    let center = UNUserNotificationCenter.current()
    center.add(request) { (error) in
       // print(error!)
    }
}
Ved Rauniyar
  • 1,539
  • 14
  • 21