1

我想在 iPad 应用程序中使用 iBeacon 功能作为信标发射器,并使用 iphone 应用程序来接收信标。我能够相应地构建这两个应用程序,但现在我遇到了一些奇怪的问题:

iBeacon Transmitter iPad 应用程序充当信标信号的发射器。我实现了一个用于选择我想传输的信标 ID 的操作表。这是代码:

#import "BeaconAdvertisingService.h"
@import CoreBluetooth;

NSString *const kBeaconIdentifier = @"identifier";

@interface BeaconAdvertisingService () <CBPeripheralManagerDelegate>
@property (nonatomic, readwrite, getter = isAdvertising) BOOL advertising;
@end

@implementation BeaconAdvertisingService {
    CBPeripheralManager *_peripheralManager;
}

+ (BeaconAdvertisingService *)sharedInstance {
    static BeaconAdvertisingService *sharedInstance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

- (instancetype)init {
    self = [super init];
    if (!self) {
        return nil;
    }
    _peripheralManager = [[CBPeripheralManager alloc] initWithDelegate:self queue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];

    return self;
}

- (BOOL)bluetoothStateValid:(NSError **)error {
    BOOL bluetoothStateValid = YES;
    switch (_peripheralManager.state) {
        case CBPeripheralManagerStatePoweredOff:
            if (error != NULL) {
                *error = [NSError errorWithDomain:@"identifier.bluetoothState"
                                             code:CBPeripheralManagerStatePoweredOff
                                         userInfo:@{@"message": @"You must turn Bluetooth on in order to use the beacon feature"}];
            }
            bluetoothStateValid = NO;
            break;
        case CBPeripheralManagerStateResetting:
            if (error != NULL) {
                *error = [NSError errorWithDomain:@"identifier.bluetoothState"
                                             code:CBPeripheralManagerStateResetting
                                         userInfo:@{@"message" : @"Bluetooth is not available at this time, please try again in a moment."}];
            }
            bluetoothStateValid = NO;
            break;
        case CBPeripheralManagerStateUnauthorized:
            if (error != NULL) {
                *error = [NSError errorWithDomain:@"identifier.bluetoothState"
                                             code:CBPeripheralManagerStateUnauthorized
                                         userInfo:@{@"message": @"This application is not authorized to use Bluetooth, verify your settings or check with your device's administration"}];
            }
            bluetoothStateValid = NO;
            break;
        case CBPeripheralManagerStateUnknown:
            if (error != NULL) {
                *error = [NSError errorWithDomain:@"identifier.bluetoothState"
                                             code:CBPeripheralManagerStateUnknown
                                         userInfo:@{@"message": @"Bluetooth is not available at this time, please try again in a moment"}];
            }
            bluetoothStateValid = NO;
            break;
        case CBPeripheralManagerStateUnsupported:
            if (error != NULL) {
                *error = [NSError errorWithDomain:@"identifier.blueetoothState"
                                             code:CBPeripheralManagerStateUnsupported
                                         userInfo:@{@"message": @"Your device does not support bluetooth. You will not be able to use the beacon feature"}];
            }
            bluetoothStateValid = NO;
            break;
        case CBPeripheralManagerStatePoweredOn:
            bluetoothStateValid = YES;
            break;
    }
    return bluetoothStateValid;
}

- (void)startAdvertisingUUID:(NSUUID *)uuid major:(CLBeaconMajorValue)major minor:(CLBeaconMinorValue)minor {
    NSError *bluetoothStateError = nil;
    if (![self bluetoothStateValid:&bluetoothStateError]) {
        NSString *title = @"Bluetooth Issue";
        NSString *message = bluetoothStateError.userInfo[@"message"];

        [[[UIAlertView alloc] initWithTitle:title
                                    message:message
                                   delegate:nil
                          cancelButtonTitle:@"OK"
                          otherButtonTitles:nil] show];
        return;
    }

    CLBeaconRegion *region;
    if (uuid && major && minor) {
        region = [[CLBeaconRegion alloc] initWithProximityUUID:uuid major:major minor:minor identifier:kBeaconIdentifier];
    } else if (uuid && major) {
        region = [[CLBeaconRegion alloc] initWithProximityUUID:uuid major:major identifier:kBeaconIdentifier];
    } else if (uuid) {
        region = [[CLBeaconRegion alloc] initWithProximityUUID:uuid identifier:kBeaconIdentifier];
    } else {
        [NSException raise:@"You must at least provide a UUID to start advertising" format:nil];
    }

    NSDictionary *peripheralData = [region peripheralDataWithMeasuredPower:nil];
    [_peripheralManager startAdvertising:peripheralData];
}

- (void)stopAdvertising {
    [_peripheralManager stopAdvertising];
    self.advertising = NO;
}

- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral {
    NSError *bluetoothStateError = nil;
    if (![self bluetoothStateValid: &bluetoothStateError]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            UIAlertView *bluetoothIssueAlert = [[UIAlertView alloc] initWithTitle:@"Bluetooth Problem"
                                                                          message:bluetoothStateError.userInfo[@"message"]
                                                                         delegate:nil
                                                                cancelButtonTitle:@"OK"
                                                                 otherButtonTitles:nil];
            [bluetoothIssueAlert show];
        });
    }
}

- (void)peripheralManagerDidStartAdvertising:(CBPeripheralManager *)peripheral error:(NSError *)error {
    dispatch_async(dispatch_get_main_queue(), ^{
        if (error) {
            [[[UIAlertView alloc] initWithTitle:@"Cannot Advertise Beacon"
                                        message:@"There was an issue starting the advertisement of the beacon"
                                       delegate:nil
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil] show];
        } else {
            NSLog(@"Advertising");
            self.advertising = YES;
        }
    });
}

据我所知,传输工作非常好......

我想响应收到的信号 ID 的 iphone 应用程序应在收到 ID 后立即引发本地通知。这在第一次运行时效果很好。我可以选择 ipad 操作表中的 3 个信标中的每一个来在 iphone 上发送此通知。但是,例如,当我重新选择第一个信标时,什么也没有发生。对于应用程序而言,应用程序每次收到信标时都做出响应至关重要。我将iphone代码设置如下:

#import "BeaconMonitoringService.h"
#import "LocationManagerService.h"

@implementation BeaconMonitoringService {
    CLLocationManager *_locationManager;
}

+ (BeaconMonitoringService *)sharedInstance {
    static dispatch_once_t onceToken;
    static BeaconMonitoringService *_sharedInstance;
    dispatch_once(&onceToken, ^{
        _sharedInstance = [[self alloc] init];
    });
    return _sharedInstance;
}

- (instancetype)init {
    self = [super init];
    if (!self) {
        return nil;
    }
    _locationManager = [[LocationManagerService sharedInstance] getLocationManager];
    return self;
}

- (void)startMonitoringBeaconWithUUID:(NSUUID *)uuid major:(CLBeaconMajorValue)major minor:(CLBeaconMinorValue)minor identifier:(NSString *)identifier onEntry:(BOOL)entry onExit:(BOOL)exit {
    CLBeaconRegion *region = [[CLBeaconRegion alloc] initWithProximityUUID:uuid major:major minor:minor identifier:identifier];
    region.notifyOnEntry = entry;
    region.notifyOnExit = exit;
    region.notifyEntryStateOnDisplay = YES;
    [_locationManager startMonitoringForRegion:region];
}

- (void)stopMonitoringAllRegions {
    for (CLRegion *region in _locationManager.monitoredRegions) {
        [_locationManager stopMonitoringForRegion:region];
    }
}

@end

位置管理器相应地抛出其委托调用,并由我在位置管理器服务中实现。

- (void)locationManager:(CLLocationManager *)manager didDetermineState:(CLRegionState)state forRegion:(CLRegion *)region {
    if ([region isKindOfClass:[CLBeaconRegion class]]) {
        CLBeaconRegion *beaconRegion = (CLBeaconRegion *)region;
        Beacon *beacon = [[BeaconDetailService sharedService] beaconWithUUID:beaconRegion.proximityUUID];
        if (beacon) {
            NSDictionary *userInfo = @{@"beacon": beacon, @"state": @(state)};
            [[NSNotificationCenter defaultCenter] postNotificationName:@"DidDetermineRegionState" object:self userInfo:userInfo];
        }

        NSLog(@"Call DidDetermine");
    }
}

- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region {
    dispatch_async(dispatch_get_main_queue(), ^{
        if ([region isKindOfClass:[CLBeaconRegion class]]) {
            CLBeaconRegion *beaconRegion = (CLBeaconRegion *)region;
            Beacon *beacon = [[BeaconDetailService sharedService] beaconWithUUID:beaconRegion.proximityUUID];
            if (beacon) {
                UILocalNotification *notification = [[UILocalNotification alloc] init];
                notification.userInfo = @{@"uuid": beacon.uuid.UUIDString};
                notification.alertBody = [NSString stringWithFormat:@"Test Beacon %@", beacon.name];
                notification.soundName = @"Default";
                [[UIApplication sharedApplication] presentLocalNotificationNow:notification];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"DidEnterRegion" object:self userInfo:@{@"beacon": beacon}];

                NSLog(@"Call DidEnter");
            }
        }
    });
}

- (void)locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region {
    dispatch_async(dispatch_get_main_queue(), ^{
        if ([region isKindOfClass:[CLBeaconRegion class]]) {
            CLBeaconRegion *beaconRegion = (CLBeaconRegion *)region;
            Beacon *beacon = [[BeaconDetailService sharedService] beaconWithUUID:beaconRegion.proximityUUID];
            if (beacon) {
                UILocalNotification *notification = [[UILocalNotification alloc] init];
                notification.alertBody = [NSString stringWithFormat:@"Test %@", beacon.name];
                [[UIApplication sharedApplication] presentLocalNotificationNow:notification];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"DidExitRegion" object:self userInfo:@{@"beacon": beacon}];
                NSLog(@"Call DidExit");
            }
        }
    });
}

当我记录委托方法的调用时,我收到以下方案:

1) DidDetermineState 被调用 2) DidEnterRegion 被调用 3) 但之后没有 DidExitRegion 被调用。

我也反复收到此错误:“PBRequester failed with Error Error Domain=NSURLErrorDomain Code=-1003 “找不到具有指定主机名的服务器。” UserInfo=0x166875e0 {NSErrorFailingURLStringKey= https://gsp10-ssl.apple.com /use , NSErrorFailingURLKey= https://gsp10-ssl.apple.com/use , NSLocalizedDescription=找不到指定主机名的服务器。, NSUnderlyingError=0x1656a9b0 "找不到指定主机名的服务器。"} "

这看起来很奇怪.. 每次我在 ipad 的操作表中选择信标时,有没有一种方法可以接收本地注释?

有趣的是,当我打开我选择的 Beacon 时,我的 iphone 会时不时地抛出本地笔记,而我在两者之间没有任何改变。突然间,DidExitRegion 被调用,DidEnterRegion 再次被调用......

谢谢你!!

4

1 回答 1

2

如果不知道更多你在做什么,就很难准确地说出发生了什么。您是在持续传输 3 个 UUID 的广告,还是只传输一次然后停止?“即使我删除了已发送的旧文件并且应该从头开始”是什么意思?这是否意味着停止对这些 UUID 进行测距然后重新启动?一些代码片段可能会有所帮助。

需要知道的重要一点是,即使没有监控处于活动状态,iOS 也会继续跟踪它看到的每个 I 信标的状态。这意味着如果 iBeacons A 和 B在您开始监视之前被 iOS 检测到,您将不会收到 didEnterRegion 通知。同样,如果在收到这样的通知后您停止监控并重新开始监控,您也不会收到新的 didEnterRegion 通知,直到 iOS 认为 iBeacon 消失并重新出现。

你确定这种全面的转变正在发生吗?尝试在 didEnterRegion 和 didExitRegion 回调中添加 NSLog 语句,以帮助查看事件触发的时间戳。

同样重要的是要了解,如果前台没有具有活动 iBeacon 监视器或范围的应用程序,iOS 可能需要很长时间才能检测到状态变化。我已经看到每个状态转换最多需要 4 分钟。如果您正在启动和停止您的发射器,请尝试在重新启动前至少等待 8 分钟,并通过日志验证您是否获得了第二次通知所需的两个转换。

于 2013-10-30T04:42:48.440 回答