didRangeBeacons call back always triggered with empty array of beacon - ios

I'm using core location library in iOS for finding beacons, I'm in beacon region and the didRangeBeacons callback is triggering but it is always returning an empty array of beacons.
Please find the attached sample code. I have beacon immediate to iPhone, but still, beacon region state is inside when app opened and immediately it is changed to outside state and we are getting an empty array in didRangeBeacons. I have included both NSLocationWhenInUseUsageDescription. The NSLocationAlwaysUsageDescription keys are in the info.plist. The application has location permission set to "always". I'm using both Estimote and Kontakt beacons. OS version is iOS 11.2.6, Device iPhone 5s, Xcode 9.2.
#import "CoreLocationViewController.h"
#interface CoreLocationViewController ()
{
CLLocationManager *locationManager;
CLBeaconRegion *beacon_region;
}
#end
#implementation CoreLocationViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(#"CoreLocationViewController viewDidLoad");
NSUUID *ProximityUUID = [[NSUUID alloc] initWithUUIDString:#"b94f62c8-1af4-11e8-accf-0ed5f89f718b"];
beacon_region = [[CLBeaconRegion alloc] initWithProximityUUID:ProximityUUID identifier:#"abqwercds"];
[beacon_region setNotifyEntryStateOnDisplay:YES];
[beacon_region setNotifyOnExit:YES];
[beacon_region setNotifyOnEntry:YES];
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
if ([CLLocationManager locationServicesEnabled]){
NSLog(#"Location Services Enabled");
if(IS_OS_8_OR_LATER){
NSLog(#"We are in LocationServicesRequestViewController IS_OS_8_OR_LATER");
NSUInteger code = [CLLocationManager authorizationStatus];
NSLog(#"CLLocationManager authorizationStatus %lu",(unsigned long)code);
if (code == kCLAuthorizationStatusNotDetermined) {
NSLog(#"kCLAuthorizationStatusNotDetermined");
[locationManager requestAlwaysAuthorization];
}
}else{
NSLog(#"We are in LocationServicesRequestViewController IS_OS_8_BELOW");
}
}else{
NSLog(#"authorizationStatus ");
}
}
#pragma mark Location Manager Delegate methods
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error{
NSLog(#"locationManager Error %#",error);
}
-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status{
NSLog(#"Status of location service is %d",status);
if ((status == kCLAuthorizationStatusAuthorizedAlways) || (status == kCLAuthorizationStatusAuthorizedWhenInUse)){
NSLog(#"location service status changed 1");
[locationManager startMonitoringForRegion:beacon_region];
[locationManager requestStateForRegion:beacon_region];
}else{
NSLog(#"location service status changed 2");
}
}
-(void)locationManager:(CLLocationManager *)manager didDetermineState:(CLRegionState)state forRegion:(CLRegion *)region{
NSLog(#"CLLocationManager Beacon Region State Determine ");
switch (state) {
case CLRegionStateUnknown:
{
NSLog(#" CLLocationManager Region state is unknown %#",region);
[locationManager stopMonitoringForRegion:beacon_region];
break;
}
case CLRegionStateInside:
{
NSLog(#" CLLocationManager Region state is In-Side %#",region);
[locationManager startRangingBeaconsInRegion:beacon_region];
}
case CLRegionStateOutside:
{
NSLog(#" CLLocationManager Region state is Out-Side %#",beacon_region);
[locationManager stopMonitoringForRegion:beacon_region];
break;
}
}
}
-(void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region{
NSLog(#" CLLocationManager Enter into Region %#",region);
[locationManager startRangingBeaconsInRegion:beacon_region];
}
- (void)locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region {
NSLog(#"didExitRegion location manager %#",region );
[locationManager stopMonitoringForRegion:beacon_region];
}
-(void)locationManager:(CLLocationManager *)manager didStartMonitoringForRegion:(CLRegion *)region{
NSLog(#"CLLocationManager Beacon Monitoring Started for the region %#",region);
}
-(void)locationManager:(CLLocationManager *)manager monitoringDidFailForRegion:(CLRegion *)region withError:(NSError *)error{
NSLog(#"CLLocationManager Monitoring of beacon region %# is failed, Error %#",region,error);
}
-(void)locationManager:(CLLocationManager *)manager rangingBeaconsDidFailForRegion:(CLBeaconRegion *)region withError:(NSError *)error{
NSLog(#"CLLocationManager ranging of beacon region %# is failed, Error %#",region.proximityUUID,error);
}
-(void)locationManager:(CLLocationManager *)manager didRangeBeacons:(NSArray<CLBeacon *> *)beacons inRegion:(CLBeaconRegion *)region{
NSLog(#"beacons %#",beacons);
}

Related

Can't get Region Monitoring to function

After trying for a while using Apple's documentation, Stackoverflow, Google, I still can't get a simple UIAlertView to show up when I enter or exit a region I am monitoring.
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.distanceFilter = kCLDistanceFilterNone;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationManager.delegate = self;
[locationManager requestAlwaysAuthorization];
for (CLRegion *monitored in [self.locationManager monitoredRegions])
[locationManager stopMonitoringForRegion:monitored];
CLLocationCoordinate2D coord;
coord.latitude = 31.521603;
coord.longitude = 33.01190;
CLCircularRegion *region = [[CLCircularRegion alloc]initWithCenter:coord radius:20 identifier:#"work"];
- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region
{
[self showMessage:[NSString stringWithFormat:#"EnterRegion: %#",region.identifier] andMessage:#"Welcome Home" andButton:#"Ok"];
}
- (void)locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region
{
[self showMessage:[NSString stringWithFormat:#"ExitRegion: %#",region.identifier] andMessage:#"Bye Bye" andButton:#"Ok"];
}
-(void)locationManager:(CLLocationManager *)manager didStartMonitoringForRegion:(CLRegion *)region {
NSLog(#"Now monitoring for %#", region.identifier);
}
- (void)locationManager:(CLLocationManager *)manager monitoringDidFailForRegion:(CLRegion *)region withError:(NSError *)error{
[self showMessage:#"msg" andMessage:[NSString stringWithFormat:#"Region Failed:%#",region.identifier] andButton:#"ok"];
}
- (void)locationManager:(CLLocationManager *)manager
didDetermineState:(CLRegionState)state forRegion:(CLRegion *)region
{
[self showMessage:[NSString stringWithFormat:#"Did Determine State: %#. state:%#",region.identifier, (state == CLRegionStateUnknown) ? #"Unknown" : (state == CLRegionStateInside) ? #"INSIDE" : #"OUTSIDE"] andMessage:#"Determined" andButton:#"Ok"];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{ }
showMessage is just a UIAlertView popping to the user.
sometimes I get monitoringDidFailForRegion when I set up the region sometimes I don't.
I was thinking if I should mark my app as using "Background Modes" for Location Updates, but this has not changed a thing. Seems like it should work, but I can never get didEnterRegion nor didExitRegion to be called.
I should point out that I updated the info.plist with the required keys:
<key>NSLocationAlwaysUsageDescription</key>
<string>Location is required for geofence</string>
Background app refresh is set to On, locations enabled. Testing outside, physically, I can't get the functions to be called.
What is it that can be wrong here? is 20 meters too short to define a region?
Could it be that region monitoring is not working for an app that is on the foreground? silencing the callbacks?

locationManager didExitRegion or locationManager didEnterRegion never called

- (void)viewDidLoad
{
[super viewDidLoad];
if([CLLocationManager locationServicesEnabled]){
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
CLLocationCoordinate2D companyCenter;
companyCenter.latitude = 23.126272;
companyCenter.longitude = 113.395568;
CLRegion* fkit = [[CLCircularRegion alloc] initWithCenter:companyCenter
radius:500 identifier:#"fkit"];
[self.locationManager startMonitoringForRegion:fkit];
}else{
NSLog(#"not support");
}
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
NSLog(#"Error : %#",error);
}
- (void)locationManager:(CLLocationManager *)manager monitoringDidFailForRegion:(CLRegion *)region withError:(NSError *)error
{
NSLog(#"Region monitoring failed with error: %#", [error localizedDescription]);
}
- (void)locationManager:(CLLocationManager *)manager didExitRegion:(nonnull CLRegion *)region
{
NSLog(#"Entered Region - %#", region.identifier);
}
- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(nonnull CLRegion *)region
{
NSLog(#"Entered Enter Region - %#", region.identifier);
}
- (void)locationManager:(CLLocationManager *)manager didStartMonitoringForRegion:(CLRegion *)region {
NSLog(#"Started monitoring %# region", region.identifier);
}
Above is my code. I run in simulator without location,and then set custome location(23.126272,113.395568) in Debug ->location item , and it never call didEnterRegion delegate . anyone can help me ?
PS:my Xcode is 7.1.1, and Console log "Started monitoring fkit region"
You are missing a few steps. You have to add an entry to your info.plist declaring that you want to use location services while your app is in the foreground, (Using the NSLocationWhenInUseUsageDescription key) and then you need to check to see if you have permission, and ask for it if you don't.
Do a search on the string "Requesting Permission to Use Location Services" in the Xcode docs for more information.
Add this line in didStartMonitoringForRegion
[self.locationManager requestStateForRegion:yourregion];

Why beacons cause Bluetooth to continuously toggle?

I am experiencing a really weird bug working with iOS and iBeacon. I have a really simple BeaconManager that ranges beacons with particular UUID, major and minor values and performs some actions once it found them. My app seems to work properly until it continuously toggle the Bluetooth status and stop doing its job. The only visible result is that the Bluetooth icon in the status bar start flickering due to Bluetooth stopping and restarting.
Where to focus attention?
This is my class definition:
#import "BeaconManager.h"
#implementation BeaconManager
- (instancetype)init {
self = [super init];
if (self) {
NSURL *beep = [[NSBundle mainBundle] URLForResource:#"beep" withExtension:#"aiff"];
soundFileURLRef = (CFURLRef) CFBridgingRetain(beep);
AudioServicesCreateSystemSoundID(soundFileURLRef, &soundFileObject);
// Initializes properties
beacon = [CLBeacon new];
foundBeacons = [NSMutableArray new];
_lastBeaconActionTimes = [[NSMutableDictionary alloc] init];
}
return self;
}
- (void)initRegion {
// Initializes the beacon region by giving it an UUID and an identifier
NSUUID *uuid = [[NSUUID alloc] initWithUUIDString:BEACON];
beaconRegion = [[CLBeaconRegion alloc] initWithProximityUUID:uuid identifier:#"beacon.region"];
// Starts looking for beacon within the region
[self.locationManager startMonitoringForRegion:beaconRegion];
}
- (void)checkBeacon {
if (!self.locationManager) {
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
if ([self.locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)])
[self.locationManager requestWhenInUseAuthorization];
}
[self initRegion];
[self locationManager:self.locationManager didStartMonitoringForRegion:beaconRegion];
}
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didStartMonitoringForRegion:(CLRegion *)region {
[self.locationManager startMonitoringForRegion:beaconRegion];
[self.locationManager startRangingBeaconsInRegion:beaconRegion];
}
- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region {
[self.locationManager startRangingBeaconsInRegion:beaconRegion];
}
- (void)locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region {
[self.locationManager stopRangingBeaconsInRegion:beaconRegion];
}
- (void)locationManager:(CLLocationManager *)manager monitoringDidFailForRegion:(CLRegion *)region withError:(NSError *)error {
NSLog(#"Failed monitoring region: %#", error);
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
NSLog(#"Location manager failed: %#", error);
}
- (void)locationManager:(CLLocationManager *)manager
didRangeBeacons:(NSArray *)beacons
inRegion:(CLBeaconRegion *)region {
if (foundBeacons.count == 0) {
for (CLBeacon *filterBeacon in beacons) {
// If a beacon is located near the device and its major value is equal to 1000 (MAJOR constant)
if (((filterBeacon.proximity == CLProximityImmediate) || (filterBeacon.proximity == CLProximityNear)))
// Registers the beacon to the list of found beacons
[foundBeacons addObject:filterBeacon];
}
}
// Did some beacon get found?
if (foundBeacons.count > 0) {
// Takes first beacon of the list
beacon = [foundBeacons firstObject];
if (([beacon.major isEqualToNumber:[NSNumber numberWithInt:MAJOR]]) && ([beacon.minor isEqualToNumber:[NSNumber numberWithInt:MINOR]])) {
// Takes the actual date and time
NSDate *now = [[NSDate alloc] init];
NSString *key = [NSString stringWithFormat:#"%# %# %#", [beacon.proximityUUID UUIDString], beacon.major, beacon.minor];
NSDate *lastBeaconActionTime = [_lastBeaconActionTimes objectForKey:key];
if ((lastBeaconActionTime == nil) || ([now timeIntervalSinceDate:lastBeaconActionTime] > MINIMUM_ACTION_INTERVAL_SECONDS)) {
[_lastBeaconActionTimes setObject:now forKey:key];
// Plays beep sound
AudioServicesPlaySystemSound(soundFileObject);
if (self.delegate) {
// Performs actions related to the beacon (i.e. delivers a coupon)
[self.delegate didFoundBeacon:self];
}
self.locationManager = nil;
}
// else [self.locationManager stopMonitoringForRegion:region];
}
[foundBeacons removeObjectAtIndex:0];
beacon = nil;
}
}
#end
Can't say for sure this is the reason why Bluetooth keeps toggling, but this part is definitely suspicious:
- (void)locationManager:(CLLocationManager *)manager didStartMonitoringForRegion:(CLRegion *)region {
[self.locationManager startMonitoringForRegion:beaconRegion];
[self.locationManager startRangingBeaconsInRegion:beaconRegion];
}
This is essentially an infinite loop. Once monitoring starts, iOS invokes the didStartMonitoring method … which starts monitoring for the very same region, which makes the iOS invoke the didStartMonitoring method again, which …
I'd start with removing the startMonitoringForRegion line from this part of your code.

CLRegionState is UnKnown When i"m in the region

I'm testing iBeacon, I've used didDetermineState: method and the CLRegionState is CLRegionStateUnknown when I'm inside the region, can anybody tell me why?
My Bluetooth is On and detecting the beacons when I range them for CLBeaconStateUnknown, sender and receiver are in range (1 Meter), here is my Implementation
-(void)locationManager:(CLLocationManager *)manager didDetermineState:(CLRegionState)state forRegion:(CLRegion *)region
{
switch (state) {
case CLRegionStateInside:
currentBeconRegion = (CLBeaconRegion *)region;
[self.locationManager startRangingBeaconsInRegion:currentBeconRegion];
NSLog(#"INSIDE the Region");//not logging
break;
case CLRegionStateOutside:
NSLog(#"OUTSIDE the Region");
break;
case CLRegionStateUnknown:
default:
NSLog(#"Region state UNKNOWN!!!"); //Logging on console
statusLabel.text = #"Region state UNKNOWN!!!";
//[self.locationManager stopRangingBeaconsInRegion:beaconRegion];
[self.locationManager startRangingBeaconsInRegion:beaconRegion];//Suceessfully ranging the beacon
break;
}
}
You say you are "inside the region" but how do you know the iBeacon is really being detected? Is Bluetooth turned on and working? Has the user allowed location access when prompted?
I would enable iBeacon ranging and log anything detected to verify your device really is seeing the iBeacon. I suspect you will either find you do not detect anything, or perhaps the iBeacon.proximity field will be returning CLProximityUnknown due to a bad calibration.
The didDetermineState gets an extra call even if no beacons have ever been detected when you start up monitoring (or if you awake the screen when notifyEntryStateOnDisplay=YES is set on you region). This is the only case where I would think you might get a CLRegionStateUnknown value. I have never seen this value returned, so I am curious under what conditions it happens. Finding the answers to my questions above may solve this. Please report back!
I've restarted both of my devices and reinstalled the app, still running into the same problem and also its not firing didEnterRegion: and didExitRegion:.
- (void)viewDidLoad
{
[super viewDidLoad];
//set peripheralManager delegate
self.peripheralManager = [[CBPeripheralManager alloc] initWithDelegate:self
queue:nil
options:nil];
//Set location managaer delegate
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
uuid = [[NSUUID alloc] initWithUUIDString:#"E01D235B-A5DB-4717-8D2F-28D5B48931F1"];
// Setup a new region with that UUID and same identifier as the broadcasting beacon
self.beaconRegion = [[CLBeaconRegion alloc] initWithProximityUUID:uuid identifier:#"testRegion"];
self.beaconRegion.notifyEntryStateOnDisplay = YES;
self.beaconRegion.notifyOnEntry = YES;
self.beaconRegion.notifyOnExit = YES;
}
#pragma mark -
#pragma mark - Peripheral Manager Delegates
-(void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral
{
switch (peripheral.state) {
case CBPeripheralManagerStatePoweredOn:
[self.locationManager startMonitoringForRegion:self.beaconRegion];
break;
case CBPeripheralManagerStatePoweredOff:
statusLabel.text = #"Bluetooth is Off";
[self clearFileds];
[self.locationManager stopMonitoringForRegion:self.beaconRegion];
break;
case CBPeripheralManagerStateUnknown:
default:
statusLabel.text = #"Bluetooth is Unsupported";
[self clearFileds];
[self.locationManager stopMonitoringForRegion:self.beaconRegion];
break;
}
}
#pragma mark -
#pragma mark - Location Manager Delecate Methods
-(void)locationManager:(CLLocationManager *)manager didStartMonitoringForRegion:(CLRegion *)region
{
[self.locationManager requestStateForRegion:self.beaconRegion];
}
-(void)locationManager:(CLLocationManager *)manager didDetermineState:(CLRegionState)state forRegion:(CLRegion *)region
{
switch (state) {
case CLRegionStateInside:
currentBeconRegion = (CLBeaconRegion *)region;
[self.locationManager startRangingBeaconsInRegion:currentBeconRegion];
NSLog(#"INSIDE the Region");
break;
case CLRegionStateOutside:
NSLog(#"OUTSIDE the Region");
break;
case CLRegionStateUnknown:
default:
NSLog(#"Region state UNKNOWN!!!");
statusLabel.text = #"Region state UNKNOWN!!!";
[self.locationManager stopRangingBeaconsInRegion:self.beaconRegion];
break;
}
}
-(void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region
{
//check if we're ranging the correct beacon
if (![self.beaconRegion isEqual:region]) { return;}
NSLog(#"didEnterRegion");
if([region isKindOfClass:[CLBeaconRegion class]])
{
currentBeconRegion = (CLBeaconRegion *)region;
if ([beaconRegion.identifier isEqualToString:#"testRegion"])
{
//send local notificaation
UILocalNotification *notice = [[UILocalNotification alloc] init];
notice.alertBody = #"Becoan Found!!!";
notice.alertAction =#"View";
[[UIApplication sharedApplication] presentLocalNotificationNow:notice];
//srart raning beacon region
[self.locationManager startRangingBeaconsInRegion:currentBeconRegion];
}
}
}
-(void)locationManager:(CLLocationManager *)manager didRangeBeacons:(NSArray *)beacons inRegion:(CLBeaconRegion *)region
{
if ([beacons count] > 0) {
int major = [beacons.firstObject major].intValue;
int minor = [beacons.firstObject minor].intValue;
if (major != self.foundBeacon.major.intValue || minor != self.foundBeacon.minor.intValue) {
NSLog(#"Found Beacon is: %#", [beacons firstObject]);
}
self.foundBeacon = [[CLBeacon alloc] init];
self.foundBeacon = [beacons firstObject];
//Set the ui
[self setFileds];
}
else //[beacon count] 0
{
statusLabel.text = #"No becaons found";
[self clearsFileds];
// [self.locationManager stopMonitoringForRegion:beaconRegion];
}
}
-(void)locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region
{
NSLog(#"didExitRegion");
if([region isKindOfClass:[CLBeaconRegion class]])
{
currentBeconRegion = (CLBeaconRegion *)region;
if ([beaconRegion.identifier isEqualToString:#"testRegion"])
{
[self.locationManager stopMonitoringForRegion:currentBeconRegion];
}
}
}
This post was written based on iOS 8 this may change in the future:
I'm posting an answer here in case someone else is having the same problem as me. I spent almost 4 hours on this in total before realizing that it was because my phone was in airplane mode.
tl;dr
If airplane mode is on, region notifications don't come through
I had the same problem before, and the answer was that I've simply forgotten to call:
[self.locationManager startMonitoringForRegion:beaconRegion];
I assumed wrongly at first that if you start ranging with:
[self.locationManager startRangingBeaconsInRegion:beaconRegion];
... and getting data for rssi, accuracy and UUID in locationManager:didRangeBeacons:inRegion: method, the CLLocationManager should be able to figure out that the phone was in that region, but apparently not. So when asking for state, with:
[self.locationManager requestStateForRegion:beaconRegion];
I got CLRegionStateUnknown for that region in the locationManager:didDetermineState:forRegion: like you did.

Monitoring overlapping regions

I use region monitoring in ios 6 and 7. It works fine, if regions are not overlapping. But if some regions are overlapping then the app calls delegate method didEnterRegion only for one region.
My code:
_locationManager = [[CLLocationManager alloc] init];
_locationManager.delegate = self;
for (XPLocationModel* locationModel in models) {
if ([self.locationManager respondsToSelector:#selector(startMonitoringForRegion:)]) {
[self.locationManager startMonitoringForRegion:locationModel.region];
} else if ([self.locationManager respondsToSelector:#selector(startMonitoringForRegion:desiredAccuracy:)]) {
[self.locationManager startMonitoringForRegion:locationModel.region desiredAccuracy:XPGeofenceMaster_DesiredAccuracy];
}
}
- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region {
NSLog(#"%s id == %#", __PRETTY_FUNCTION__, region.identifier);
}
- (void)locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region {
NSLog(#"%s", __PRETTY_FUNCTION__);
}
If you want, you can use the requestStateForRegion: method to get an update about all of your states, something like this. However, you better be prepared for enter and exit to be called multiple times.
- (void)requestStateForAllLocations
{
for (CLRegion *region in self.locationManager.monitoredRegions) {
[self.locationManager requestStateForRegion:region];
}
}

Resources