当iBeacon范围是“立即”还是“接近”时,如何通知用户?

时间:2016-01-07 10:08:09

标签: ios objective-c ibeacon

用户只有在距离信标足够近时才会收到通知,因为 didEnterRegion 无法正常工作。 我的代码是这样的:

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];
}

但通知会继续发送给用户。我怎么才能收到一次通知?

1 个答案:

答案 0 :(得分:3)

1。向控制器添加标志

接口:

@property (nonatomic) BOOL userNotified;

实现:

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。使用GCD(Grand Central Dispatch)

使用此方法,每个应用启动时代码只会执行一次。

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];
    }
});