Search code examples
iosobjective-cuilocalnotification

UILocalNotification not called when is in background


I'm try to fire UILocalNotification when app is in background and is in active state. I use following:

In App Delegate i want to "catch" notification callback by this (it's not called):

- (void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary*)userInfo{

    NSLog(@"recieve-old-notif-here");

}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{


    NSLog(@"recieve-old-notif");
}

Here is how i declared local notification:

NSString *strToShow = [NSString stringWithFormat:@"Время вставать"];


UILocalNotification *notification = [[UILocalNotification alloc] init];
notification.fireDate = [NSDate dateWithTimeIntervalSinceNow:15];

notification.alertBody = strToShow;
notification.timeZone = [NSTimeZone defaultTimeZone];
notification.soundName = UILocalNotificationDefaultSoundName;
[[UIApplication sharedApplication] scheduleLocalNotification:notification];

Please note that i already achieve that task with iOS 10 notifications, but i want to support this feature on older version devices.

So, my delegate methods suppose to call but their does not, why?


Solution

  • Add below code to the didFinishLaunchingWithOptions method in delegate :

    ifdef __IPHONE_8_0

    //Right, that is the point
    UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound) categories:nil];
    [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    

    else

    //register to receive notifications
    UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound;
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:myTypes];
    

    endif

    and below delegate methods;

    #ifdef __IPHONE_8_0
    - (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
    {
        //register to receive notifications
        [application registerForRemoteNotifications];
    }
    
    - (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void(^)())completionHandler
    {
        //handle the actions
        if ([identifier isEqualToString:@"declineAction"]){
        }
        else if ([identifier isEqualToString:@"answerAction"]){
        }
    }
    #endif