Search code examples
iosgeolocationcllocationmanageruilocalnotification

What's the difference of these geo-based notification approaches on iOS?


I'm looking for a way to implement geo-based notifications on iOS.
I found two ways but I couldn't figure out which one is the best and the difference.

1: Using CLLocationManager's startMonitoring Like this tutorial. https://www.raywenderlich.com/136165/core-location-geofencing-tutorial

2: Using CLLocationManager's startMonitoring and UILocalNotification's region.

Like this code:

    UILocalNotification *localNotif = [[UILocalNotification alloc] init];
    if (localNotif == nil)
        return;
    localNotif.alertBody = [NSString stringWithFormat:@"Hello!"];
    localNotif.soundName = UILocalNotificationDefaultSoundName;
    localNotif.applicationIconBadgeNumber = 1;

    CLCircularRegion *region = nil;

    CLLocationCoordinate2D location = CLLocationCoordinate2DMake(geoPoint.latitude,
                                                                 geoPoint.longitude);
    if (CLLocationCoordinate2DIsValid(location)){
        region = [[CLCircularRegion alloc] initWithCenter:location
                                                   radius:50.0
                                               identifier:@"region1"];

        region.notifyOnExit = NO;

        localNotif.region = region;
        localNotif.regionTriggersOnce = YES;
        [[UIApplication sharedApplication] scheduleLocalNotification:localNotif];

    } else {
        NSDictionary *info = @{NSLocalizedDescriptionKey:@"Invalid coordinate info."};
        NSError *error = [NSError errorWithDomain:@"InvalidCLLocationError"
                                             code:1999
                                         userInfo:info];
    }

Solution

  • In order to show notifications when the app is dismissed you should use the UILocalNotification approach. This is because CLLocationManager's startMonitoring will stop working after your app is dismissed. You're basically setting up a Geofence when using UILocalNotification.

    You'll have to implement CLLocationManager's didEnterRegion and didExitRegion delegate methods. In those methods you'll set the local notifications.

    Please note: As of iOS 10, UILocalNotification is deprecated. Please use UNNotificationRequest instead.

    https://developer.apple.com/reference/uikit/uilocalnotification