I created a localNotification to launch a message and it is not called at the good moment. What is strange is that when I put a date in the future, it never fire it, but if I put a date in the past, it fire it at the launch of the app...
Main function :
...
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];
...
Function receive local notification :
- (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];
});
}
It doesn't work correctly...
Here is the answer :
You have to simply authorise it. You have to put that lines just before initialize the localNotification in you main function :
UIUserNotificationType types = UIUserNotificationTypeBadge |
UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
UIUserNotificationSettings *mySettings =
[UIUserNotificationSettings settingsForTypes:types categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:mySettings];