this issue has been driving me crazy. What I am trying to do is trigger a notification when the user enter in a region. However, what I want is, if the user is using the app show an alert message and if the app is in background shows a local notification.
Here is my code:
- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region
{
UIApplication *app = [UIApplication sharedApplication];
if (app.applicationState == UIApplicationStateActive)
{
NSURL *musicFile = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"Alarm" ofType:@"caf"]];
AVAudioPlayer *audioFile = [[AVAudioPlayer alloc] init];
audioFile = [[AVAudioPlayer alloc] initWithContentsOfURL:musicFile error:NULL];
[audioFile play];
UIAlertView *arrivingDestinationAlert = [[UIAlertView alloc] initWithTitle: @"Arriving" message:[NSString stringWithFormat:@"Alert"] delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
[arrivingDestinationAlert show];
}else if(app.applicationState == UIApplicationStateBackground || app.applicationState == UIApplicationStateInactive)
{
UILocalNotification *notification = [[UILocalNotification alloc] init];
notification.alertBody = [NSString stringWithFormat:@"%d to reach your destination", self.distToRemind];
notification.alertAction = @"Destination Approaching";
notification.hasAction = YES;
notification.soundName = UILocalNotificationDefaultSoundName;
[app presentLocalNotificationNow:notification];
}
[manager stopMonitoringForRegion:region];
}
What I was doing before was working. Which was lunch an local notification without asking whether the state of the app was background or active. I was just lunching the notification as soon the didEnterRegion
was trigger. However now I can get it work.
Am I missing anything?
I think you are checking for the active state in the wrong spot. I do something very similar, but I check for active state in the AppDelegate when the notification fires. You should intercept the local notification in
-didReceiveLocalNotification
. If the state is active, push your UIAlertView there. If you fire the alert from the -didEnterRegion or -didExitRegion from the background, it will never be seen.