Photunix
Photunix

Reputation: 227

How to notify user when iBeacon range is "Immediate" or "near"?

Users will only get notified when they are close enough to the beacon, since then didEnterRegion dose not work properly. My code is like this:

if ([region isKindOfClass:[CLBeaconRegion class]] && ([beaconRegionInStringFormat isEqualToString:@"Immediate"] || [beaconRegionInStringFormat isEqualToString:@"Near"]))
{
    UILocalNotification *notification = [[UILocalNotification alloc] init];
    notification.alertBody = @"Please open the application";
    [[UIApplication sharedApplication] presentLocalNotificationNow:notification];
}

But the notification will keep sending to users. How can I only get notified once?

Upvotes: 1

Views: 99

Answers (1)

bevoy
bevoy

Reputation: 751

1. Adding a flag to your controller

Interface:

@property (nonatomic) BOOL userNotified;

Implementation:

if (!self.userNotified && [region isKindOfClass:[CLBeaconRegion class]] && ([beaconRegionInStringFormat isEqualToString:@"Immediate"] || [beaconRegionInStringFormat isEqualToString:@"Near"]))
{
    UILocalNotification *notification = [[UILocalNotification alloc] init];
    notification.alertBody = @"Please open the application";
    [[UIApplication sharedApplication] presentLocalNotificationNow:notification];
    self.userNotified = YES;
}

2. Using the GCD (Grand Central Dispatch)

Using this method the code will be executed only once per app launch.

static dispatch_once_t onceToken;
dispatch_once (&onceToken, ^{
    if ([region isKindOfClass:[CLBeaconRegion class]] && ([beaconRegionInStringFormat isEqualToString:@"Immediate"] || [beaconRegionInStringFormat isEqualToString:@"Near"]))
    {
        UILocalNotification *notification = [[UILocalNotification alloc] init];
        notification.alertBody = @"Please open the application";
        [[UIApplication sharedApplication] presentLocalNotificationNow:notification];
    }
});

Upvotes: 3

Related Questions