I'm new at iOS and Cocoa Programming and today I wanted to build a small iOS App for testing Local Notifications. The notifications just work fine and everything is working like I have expected. My only problem is, that the method application:didReceivedLocalNotification doesn't want to be called :D
The implementation works like that: the UI has a slider, where the User can define a time value, measured in seconds. After setting the value on the slider, the LocalNotification should be fired in xx seconds. When I press the home button the Notification appears dead on time. But when the Application is on foreground the notification doesn't appear. I have implemented the method application:didReceivedLocalNotification and tested the calling of the method by putting an NSLog(@"YEEEAAH"); at the beginning of the method, but there is no output on the terminal.
The segue seems to work, too. When I put the line at the end of sliderTouched: the segue performs.
Here is my code:
- (IBAction)sliderTouched:(UISlider *)sender {
float seconds = [sender value];
self.secondLabel.text = [NSString stringWithFormat:@"%d sec.", (int)seconds];
UIApplication *theApplication = [UIApplication sharedApplication];
UILocalNotification * theNotification = [[UILocalNotification alloc] init];
[theApplication cancelAllLocalNotifications];
NSDate *fireDate = [NSDate dateWithTimeIntervalSinceNow:(int)seconds];
theNotification.fireDate = fireDate;
theNotification.timeZone = [NSTimeZone defaultTimeZone];
theNotification.alertBody = @"Lalalala";
theNotification.soundName = UILocalNotificationDefaultSoundName;
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:fireDate];
NSInteger hour = [components hour]%12;
NSInteger minute = [components minute];
NSInteger second = [components second];
self.timeLabel.text = [NSString stringWithFormat:@"%02i:%02i:%02i", hour, minute, second];
[theApplication scheduleLocalNotification:theNotification];
}
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
if (application.applicationState == UIApplicationStateActive) {
[self performSegueWithIdentifier:@"modalView" sender:nil];
}
}
Two conditions :-
1)If your application is in the Not-Running state , then didFinishLaunchingWithOptions function is called and then didReceiveLocalNotification is called
2)if your application is in the Running State i.e. if it is in the foreground or background , then didReceiveLocalNotification is called
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With