2017-02-28 2 views
0

J'ai créé une notification locale pour lancer un message et elle n'est pas appelée au bon moment. Ce qui est étrange c'est que quand je mets une date dans le futur, elle ne la déclenche jamais, mais si je mets une date dans le passé, elle se déclenche au lancement de l'application ...La notification locale ne fonctionne pas correctement. La fonction didReceiveLocalNotification n'est pas appelée au bon moment

Fonction principale:

... 
NSDateComponents *comps = [NSDateComponents new]; 
    [comps setDay:28]; 
    [comps setMonth:02]; 
    [comps setYear:2017]; 
    [comps setHour:16]; 
    [comps setMinute:50]; 
    [comps setSecond:00]; 

    NSDate *alarmDate = [[NSCalendar currentCalendar] dateFromComponents:comps]; 
    NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init]; 
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; 
    // or @"yyyy-MM-dd hh:mm:ss a" if you prefer the time with AM/PM 

    NSDate *currentDate= [NSDate date]; 
    UILocalNotification *localNotification = [[UILocalNotification alloc] init]; 

    // Set the fire date/time 
    [localNotification setFireDate:alarmDate]; 
    [localNotification setTimeZone:[NSTimeZone defaultTimeZone]]; 

    localNotification.applicationIconBadgeNumber=1; 

    // Setup alert notification 
    [localNotification setAlertAction:@"Open App"]; 
    // [localNotification setAlertBody:[randonQuotesDic objectForKey:@"Rajneesh"]]; 
    [localNotification setAlertBody:@"You had set a Local Notification on this time"]; 

    localNotification.soundName=UILocalNotificationDefaultSoundName; 
    [localNotification setHasAction:YES]; 
    UIApplication *app=[UIApplication sharedApplication]; 
    [app scheduleLocalNotification:localNotification]; 
... 

Fonction recevoir une notification locale:

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification 
{ 
    UIApplicationState state = [application applicationState]; 
    // check state here 

    if(state ==UIApplicationStateBackground){ 

    } 
    dispatch_async(dispatch_get_main_queue(), ^{ 

     UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Wake" message:notification.alertBody delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil]; 
     [alertView show]; 
    }); 
} 

Il n'est la réponse fonctionne pas correctement ...

Répondre

0

ici:

Vous devez simplement l'autoriser. Vous devez mettre ces lignes juste avant d'initialiser le localNotification dans votre fonction principale:

UIUserNotificationType types = UIUserNotificationTypeBadge | 
    UIUserNotificationTypeSound | UIUserNotificationTypeAlert; 

    UIUserNotificationSettings *mySettings = 
    [UIUserNotificationSettings settingsForTypes:types categories:nil]; 

    [[UIApplication sharedApplication] registerUserNotificationSettings:mySettings];