Search code examples
iosuilocalnotificationcllocationregionbackground-foreground

location based `local Notification` works in the `background` but not in the `foreground`


Notification should activate whenever the location is near, but it only works in the background. Even though the triggering event happens in both the foreground and background.

- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region {

//implement local notification:
UIApplication *app = [UIApplication sharedApplication];
UILocalNotification *notification = [[UILocalNotification alloc] init];
[[UIApplication sharedApplication] cancelAllLocalNotifications];

if (notification == nil)
    return;
notification.fireDate = [NSDate date];
notification.timeZone = [NSTimeZone defaultTimeZone];
notification.alertBody = [selectedTask discription];
notification.alertAction = [selectedTask taskName];
notification.soundName = UILocalNotificationDefaultSoundName;
notification.applicationIconBadgeNumber = 1;
[app presentLocalNotificationNow:notification];
localNotification = nil;

}

Solution

  • From inside your didReceiveLocalNotification method you can display an alert to the user since notifications are not handled if the app is in the foreground.

    UIAlertView *alert = [[UIAlertView alloc]
            initWithTitle: @"Something"
            message: @"Something else you want to tell the user"
            delegate:self
            cancelButtonTitle:@"OK"
            otherButtonTitles:nil];
    [alert show];