Skip to content
Alann Maulana edited this page Dec 6, 2016 · 1 revision

Starting ranging is very easy, we need to provide a beacon region that will define which beacons to scan for. Let’s say we’re interested in all beacons. For that, we can define a beacon region—by proximity UUID only. Let’s just use the default Cubeacon UUID: CB10023F-A318-3394-4199-A8730C7C1AEC.

Let’s go to the ViewController implementation file and set up a second beacon manager. Also, this time, we’ll create a dedicated property to hold the beacon region, since we’ll be using it in two places: to start, and to stop ranging. This goes inside the ViewController class:

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.beaconManager = [[CBBeaconManager alloc] init];
    self.beaconManager.delegate = self;
    self.region = [[CBRegion alloc] initWithProximityUUID:[[NSUUID alloc] initWithUUIDString:CUBEACON_UUID]
                                                    major:1
                                                    minor:1
                                               identifier:@"com.eyro.cubeacon.ranging_region"];
    [self.beaconManager requestAlwaysAuthorization];
}

Now, the code to start and stop ranging as the activity appears and disappears on screen. You need to implement CBServiceListener before connecting to service. This too goes inside the RangingActivity class:

@interface RangingViewController () <CBBeaconManagerDelegate>

@property (nonatomic, strong) CBBeaconManager *beaconManager;
@property (nonatomic, strong) CBRegion *region;

@end

@implementation RangingViewController

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    [self.beaconManager startRangingBeaconsInRegion:self.region];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];

    [self.beaconManager stopRangingBeaconsInRegion:self.region];
}

@end

Having the list pre-sorted by the Cubeacon SDK, and with all the prep work we’ve performed, the ranging delegate turns out to be quite simple:

- (void)didRangeBeacons:(NSArray<CBBeacon *> *)beacons inRegion:(CBRegion *)region {
    NSLog(@"Found %d beacon(s) in region:%@", beacons.count, region);
}
Clone this wiki locally