Inconsistent behaviour by proximity API - iOS iBeacon - ios

I am converting an iOS device into iBeacon and then using core location' ranging API to detect beacon' proximity. Now, this works but I see an unpredictable behaviour where sometimes at a defined distance (say 10 meters away) I see No Beacon sometimes Far Beacon and some times Near Beacon.
Is there a way to make this behaviour more consistent?
- (void)viewDidLoad {
[super viewDidLoad];
self.beaconSwitch.on = NO;
self.beaconView.backgroundColor = [UIColor clearColor];
self.peripheralManager = [[CBPeripheralManager alloc] initWithDelegate:self queue:nil];
BeaconRegion *beaconRegion = [[BeaconRegion alloc] init];
self.beaconRegion = [[CLBeaconRegion alloc] initWithProximityUUID:beaconRegion.uuid major:[beaconRegion.major shortValue] minor:[beaconRegion.minor shortValue] identifier:beaconIdentifier];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[self.peripheralManager stopAdvertising];
}
- (IBAction)doneButtonPressed:(id)sender {
[self dismissViewControllerAnimated:YES completion:nil];
}
- (IBAction)beaconSwitchPressed:(id)sender {
if (self.beaconSwitch.on == true) {
self.beaconView.beaconState = BNBeaconStateBroadcasting;
NSDictionary *data = [self.beaconRegion peripheralDataWithMeasuredPower:nil];
[self.peripheralManager startAdvertising:data];
} else {
self.beaconView.beaconState = BNBeaconStateStop;
[self.peripheralManager stopAdvertising];
}
}
Here is how I am converting my iOS device into a beacon:
And here is how I am getting its proximity:
- (void)viewDidLoad {
[super viewDidLoad];
BeaconRegion *beaconRegion = [[BeaconRegion alloc] init];
self.beaconRegion = [[CLBeaconRegion alloc] initWithProximityUUID:beaconRegion.uuid identifier:beaconIdentifier];
self.beaconRegion.notifyOnEntry = YES;
self.beaconRegion.notifyOnExit = YES;
self.beaconRegion.notifyEntryStateOnDisplay = YES;
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
self.detectionSwitch.on = NO;
}
- (IBAction)beaconDetectionSwitchPressed:(id)sender {
if (self.detectionSwitch.isOn) {
[self.locationManager startMonitoringForRegion:self.beaconRegion];
[self.locationManager requestStateForRegion:self.beaconRegion];
} else {
self.lastProximity = CLProximityUnknown;
[self.locationManager stopMonitoringForRegion:self.beaconRegion];
[self.locationManager stopRangingBeaconsInRegion:self.beaconRegion];
self.titleLabel.text = #"";
self.messageLabel.text = #"";
}
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[self.locationManager stopMonitoringForRegion:self.beaconRegion];
[self.locationManager stopRangingBeaconsInRegion:self.beaconRegion];
self.locationManager = nil;
}
- (void)locationManager:(CLLocationManager *)iManager didEnterRegion:(CLRegion *)iRegion {
NSLog(#"Detected a beacon");
if (![self.beaconRegion isEqual:iRegion]) {
return;
}
NSLog(#"Entered into the beacon region = %#", iRegion);
[self.locationManager startRangingBeaconsInRegion:self.beaconRegion];
}
- (void)locationManager:(CLLocationManager *)manager didRangeBeacons:(NSArray *)beacons inRegion:(CLBeaconRegion *)region {
NSLog(#"Ranging beacon successful");
if (beacons.count > 0) {
CLBeacon *nearestBeacon = beacons[0];
CLProximity currentProximity = nearestBeacon.proximity;
if (currentProximity == self.lastProximity) {
NSLog(#"No Change in Beacon distance");
} else {
self.lastProximity = currentProximity;
[self updateUserAboutProximity];
}
} else {
self.lastProximity = CLProximityUnknown;
}
}
- (void)updateUserAboutProximity {
NSString *title = #"--";
NSString *message = #"--";
switch (self.lastProximity) {
case CLProximityUnknown:{
title = #"No Beacon";
message = #"There is no nearby beacon";
}
break;
case CLProximityImmediate:{
title = #"Immediate Beacon";
message = #"You are standing immediate to video wall!";
}
break;
case CLProximityNear:{
if (self.isServerCallOn) {
title = #"Near Beacon";
message = #"You are standing near to video wall!";
} else {
title = #"Near Beacon";
message = #"You are standing near to video wall! Initiating a server call.";
if (!self.ignoreSeverCallTrigger) {
self.isServerCallOn = YES;
[self talkToServer];
} else {
NSLog(#"Ignoring server call trigger");
message = #"Ignoring server call trigger!";
}
}
}
break;
case CLProximityFar:{
title = #"Far Beacon";
message = #"You are standing far from video wall!";
}
break;
default:
break;
}
self.titleLabel.text = title;
self.messageLabel.text = message;
}
- (void)locationManager:(CLLocationManager *)manager didDetermineState:(CLRegionState)state forRegion:(CLRegion *)region {
if (state == CLRegionStateInside) {
NSLog(#"Starting Ranging");
[self.locationManager startRangingBeaconsInRegion:self.beaconRegion];
}
}
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
if (![CLLocationManager locationServicesEnabled]) {
NSLog(#"Location Service Not Enabled");
}
if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedAlways) {
NSLog(#"Location Service Not Authorized");
}
}

For now, I have put a condition on received signal strength indicator (rssi) value and accepting anything > -60 in Near proximity to make the distance little more predictable. So, within Nearby proximity also I trigger my action if rssi > -60.

Related

How to solve the issue with beacon?

My Problem: When I click the button, my phone will show a progress view(ask me come close the beacon), and when I come close the beacon, my phone will show a view(checkmark), and then remove the view 1.5s later. Now the view can show normally first, but when I take my phone far away from the beacon, and the view(show checkmark) will show 1s later. It's a big problem out of my mind.
My code:
onClick button
- (IBAction)chooseBLEAction:(id)sender {
self.locationManager = [CLLocationManager new];
[self _initBeaconRegion];
if (([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse ||
[CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways ||
[CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined) &&
[self.locationManager respondsToSelector:#selector(requestAlwaysAuthorization)])
{
[self _start];
if (self.bluetoothIsOpen) {
[self _createProgressView];
}
}else {
[self.locationManager requestWhenInUseAuthorization];
}
}
- (void)_start {
[self.locationManager startRangingBeaconsInRegion:self.targetBeaconRegion];
}
- (void)_stop {
[self.locationManager stopRangingBeaconsInRegion:self.targetBeaconRegion];
}
CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didRangeBeacons:(NSArray<CLBeacon *> *)beacons inRegion:(CLBeaconRegion *)region {
NSLog(#"searching for beacon !");
CLBeacon *foundBeacon = [CLBeacon new];
foundBeacon = [beacons firstObject];
if (foundBeacon) {
NSLog(#"found beacon !");
switch (foundBeacon.proximity) {
case CLProximityUnknown:
break;
case CLProximityFar:
break;
case CLProximityNear:
break;
case CLProximityImmediate:
{
[self _stop];
NSLog(#"Immediate beacon !");
AudioServicesPlaySystemSound(1051);
[self.myProgressView removeFromSuperview];
[self _createSuceessProgressView];
self.removeProgressViewTimer = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:#selector(_removeSuccessProgressView) userInfo:nil repeats:NO];
break;
}
}
}
}
create progress view (close the beacon)
- (void)_createProgressView {
NSString *title = #"Please close the beacon";
self.myProgressView = [MRProgressOverlayView showOverlayAddedTo:self.view title:title mode:MRProgressOverlayViewModeIndeterminate animated:YES];
}
create success view
- (void)_createSuceessProgressView {
NSString *title = #"Success!";
self.suceessProgressView = [MRProgressOverlayView showOverlayAddedTo:self.view title:title mode:MRProgressOverlayViewModeCheckmark animated:YES];
}
remove success view 1.5s later
- (void)_removeSuccessProgressView {
[self.removeProgressViewTimer invalidate];
[self.suceessProgressView removeFromSuperview];
}

Understanding iBeacons in iOS: didDetermineState and didEnterRegion events

Part one:
I have written the following code to monitor iBeacons. I would like to detect the didEnterRegion and didExitRegion event. However it never happens. Would you be able to take a look at the code and suggest what could be missing?
I use the Apple AirLocate sample code to configure one device as iBeacon and perform the following steps to test my code:
Steps:
compile and execute AirLocate sample code on device B
compile and execute this code on device A
in device B use AirLocate app to configure device as iBeacon choosing the following UUID: "74278BDA-B644-4520-8F0C-720EAF059935"
Results:
state inside message
Expected results:
state inside message
did enter region
Why is that?
Those are my plist entries:
Code:
#import "BeaconMonitoring.h"
#implementation BeaconMonitoring
- (instancetype)init
{
self = [super init];
if (self) {
self.locationManager = [[CLLocationManager alloc] init];
if([self.locationManager respondsToSelector:#selector(requestAlwaysAuthorization)]) {
[self.locationManager requestAlwaysAuthorization];
}
self.locationManager.delegate = self;
self.locationManager.pausesLocationUpdatesAutomatically = NO;
self.monitoredRegions = [[NSMutableArray alloc] initWithCapacity:10];
}
return self;
}
- (void) startRangingForBeacons{
NSLog(#"in startRangingForBeacons");
[self.locationManager startUpdatingLocation];
[self startMonitoringForRegion:[[NSUUID alloc] initWithUUIDString:#"74278BDA-B644-4520-8F0C-720EAF059935"] :#"b"];
}
- (void) startMonitoringForRegion:(NSUUID*)beaconUUID :(NSString*)regionIdentifier{
/**
Alternatively:
CLBeaconRegion *beaconRegion = [[CLBeaconRegion alloc] initWithProximityUUID:#"xxxx"
major:10
minor:20
identifier:#"name"]
**/
// Override point for customization after application launch.
CLBeaconRegion *beaconRegion = [[CLBeaconRegion alloc] initWithProximityUUID:beaconUUID identifier:regionIdentifier];
beaconRegion.notifyEntryStateOnDisplay = NO;
beaconRegion.notifyOnEntry = YES;
beaconRegion.notifyOnExit = YES;
[self.locationManager startMonitoringForRegion:beaconRegion];
[self.locationManager startRangingBeaconsInRegion:beaconRegion];
[self.monitoredRegions addObject:beaconRegion];
}
- (void) stopRangingForbeacons{
NSLog(#"in stopRangingForbeacons");
[self.locationManager stopUpdatingLocation];
for (int i=0; i < [self.monitoredRegions count]; i++) {
NSObject * object = [self.monitoredRegions objectAtIndex:i];
if ([object isKindOfClass:[CLBeaconRegion class]]) {
CLBeaconRegion * region = (CLBeaconRegion*)object;
[self.locationManager stopMonitoringForRegion:region];
[self.locationManager stopRangingBeaconsInRegion:region];
}
else{
NSLog(#"Serious error, should never happen!");
}
}
}
#pragma CLLocationManagerDelegate
-(void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region {
[manager startRangingBeaconsInRegion:(CLBeaconRegion*)region];
[self.locationManager startUpdatingLocation];
NSLog(#"You entered the region.");
}
-(void)locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region {
[manager stopRangingBeaconsInRegion:(CLBeaconRegion*)region];
[self.locationManager stopUpdatingLocation];
NSDictionary * notificationData = #{ #"value" : #"exitedRegion"};
[[NSNotificationCenter defaultCenter] postNotificationName:#"dataUpdate" object:nil userInfo:notificationData];
NSLog(#"You exited the region.");
// [self sendLocalNotificationWithMessage:#"You exited the region."];
}
- (void) locationManager:(CLLocationManager *)manager didDetermineState:(CLRegionState)state forRegion:(CLRegion *)region
{
NSLog(#"did determine state");
switch (state) {
case CLRegionStateInside:
NSLog(#"state inside");
break;
case CLRegionStateOutside:
NSLog(#"state outside");
break;
case CLRegionStateUnknown:
NSLog(#"state unknown");
break;
default:
NSLog(#"Default case: Region unknown");
break;
}
}
-(void)locationManager:(CLLocationManager *)manager didRangeBeacons:(NSArray *)beacons inRegion:(CLBeaconRegion *)region {
NSLog(#"Did range %lu beacon in region %#", (unsigned long)[beacons count], region.identifier);
NSString * visibleInformation = [NSString stringWithFormat:#"(%lu)", (unsigned long)[beacons count]];
for (int i=0; i<[beacons count]; i++) {
CLBeacon *beacon = [beacons objectAtIndex:i];
if ([beacons count] == 1) {
NSNumber * distance = [NSNumber numberWithFloat:beacon.accuracy];
visibleInformation = [NSString stringWithFormat:#"%i-%i is %f", beacon.major.intValue, beacon.minor.intValue, distance.doubleValue];
}
else{
visibleInformation = [visibleInformation stringByAppendingString:[NSString stringWithFormat:#" %i-%i ", beacon.major.intValue, beacon.minor.intValue]];
}
}
}
#end
Part two:
I had a look at the AirLocate source code to understand if there was something that I had to trigger in the state inside message to get the monitoring working properly. However I found that the ** didDetermineState** method is implemented in the AppDelegate.
Why is that?
- (void)locationManager:(CLLocationManager *)manager didDetermineState:(CLRegionState)state forRegion:(CLRegion *)region
{
/*
A user can transition in or out of a region while the application is not running. When this happens CoreLocation will launch the application momentarily, call this delegate method and we will let the user know via a local notification.
*/
UILocalNotification *notification = [[UILocalNotification alloc] init];
if(state == CLRegionStateInside)
{
notification.alertBody = NSLocalizedString(#"You're inside the region", #"");
}
else if(state == CLRegionStateOutside)
{
notification.alertBody = NSLocalizedString(#"You're outside the region", #"");
}
else
{
return;
}
/*
If the application is in the foreground, it will get a callback to application:didReceiveLocalNotification:.
If it's not, iOS will display the notification to the user.
*/
[[UIApplication sharedApplication] presentLocalNotificationNow:notification];
}
Assumption: R = Region made by B and listened to by A
Case 1
IF A was started before B:
app A should tell you determine state for region R = outside
app A should run didEnter Region R
case 2
IF A was infact started after B:
it should only run determineState Region R = inside
the end. There is no 2 here because it never enters the range. it was started inside of it

Unable to detect ibeacon on iphone 6

Hi i have below code which works fine on iPod touch 5, but same code is not working on iPhone 6, i done research on same issue but i have not found anything useful. both devices have latest iOS.
Both devices have iOS 8
// MapViewController.m
// SidebarDemo
//
// Created by Simon on 30/6/13.
// Copyright (c) 2013 Appcoda. All rights reserved.
//
#import "PetFinderViewController.h"
#import "SWRevealViewController.h"
#interface PetFinderViewController ()
#end
#implementation PetFinderViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor colorWithRed:(51/255.0) green:(51/255.0) blue:(51/255.0) alpha:1] ;
self.title = #"Pet Finder";
// Change button color
//_sidebarButton.tintColor = [UIColor colorWithWhite:0.96f alpha:0.2f];
// Set the side bar button action. When it's tapped, it'll show up the sidebar.
_sidebarButton.target = self.revealViewController;
_sidebarButton.action = #selector(revealToggle:);
// Set the gesture
[self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];
// Check if beacon monitoring is available for this device
if (![CLLocationManager isMonitoringAvailableForClass:[CLBeaconRegion class]]) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Monitoring not available" message:nil delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil]; [alert show]; return;
}
else
{
// Initialize location manager and set ourselves as the delegate
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
// Create a NSUUID
NSUUID *uuid = [[NSUUID alloc] initWithUUIDString:#"ebefd083-70a2-47c8-9837-e7b5634df524"];
// Setup a new region AND start monitoring
str_beaconIdentifier = #"in.appstute.marketing";
self.myBeaconRegion = [[CLBeaconRegion alloc] initWithProximityUUID:uuid major:1 minor:1 identifier:str_beaconIdentifier];
self.myBeaconRegion.notifyEntryStateOnDisplay = YES;
self.myBeaconRegion.notifyOnEntry = YES;
self.myBeaconRegion.notifyOnExit = YES;
[self.locationManager startMonitoringForRegion:self.myBeaconRegion];
self.lbl_rangeStatus.text = #"Finding Your Pet";
self.lbl_regionStatus.text = #"";
self.lbl_distance.text = #"";
}
}
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
if (![CLLocationManager locationServicesEnabled]) {
NSLog(#"Couldn't turn on ranging: Location services are not enabled.");
}
if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorized) {
NSLog(#"Couldn't turn on monitoring: Location services not authorised.");
[self.locationManager requestAlwaysAuthorization];
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Core Location Delegate methods
- (void)locationManager:(CLLocationManager*)manager didEnterRegion:(CLRegion *)region
{
UILocalNotification *notify = [[UILocalNotification alloc] init];
notify.alertBody = #"You are near your Pet's region.";
notify.soundName = UILocalNotificationDefaultSoundName;
[[UIApplication sharedApplication] presentLocalNotificationNow:notify];
// We entered a region, now start looking for our target beacons!
//self.statusLabel.text = #"Finding beacons.";
self.lbl_rangeStatus.text = #"Pet Found";
self.lbl_regionStatus.text = #"Status : Entered Region";
[self.locationManager startRangingBeaconsInRegion:self.myBeaconRegion];
//Opening camera
/*if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
{
UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];
imagePicker.delegate = self;
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
imagePicker.allowsEditing = YES;
//[self presentModalViewController:imagePicker animated:YES];
[self presentViewController:imagePicker animated:YES completion:nil];
}
else
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Camera Unavailable"
message:#"Unable to find a camera on your device."
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil, nil];
[alert show];
alert = nil;
}*/
}
-(void)locationManager:(CLLocationManager*)manager didExitRegion:(CLRegion *)region
{
UILocalNotification *notify = [[UILocalNotification alloc] init];
notify.alertBody = #"You are far away from your Pet's region.";
notify.soundName = UILocalNotificationDefaultSoundName;
[[UIApplication sharedApplication] presentLocalNotificationNow:notify];
// Exited the region
//self.statusLabel.text = #"None found.";
self.lbl_rangeStatus.text = #"Pet Not Found";
self.lbl_regionStatus.text = #"Status : Exited Region";
[self.locationManager stopRangingBeaconsInRegion:self.myBeaconRegion];
}
-(void)locationManager:(CLLocationManager*)manager didRangeBeacons:(NSArray*)beacons inRegion:(CLBeaconRegion*)region
{
CLBeacon *foundBeacon = [beacons firstObject];
// Retrieve the beacon data from its properties
NSString *uuid = foundBeacon.proximityUUID.UUIDString;
NSString *major = [NSString stringWithFormat:#"%#", foundBeacon.major];
NSString *minor = [NSString stringWithFormat:#"%#", foundBeacon.minor];
NSLog(#"uuid=%#, major=%#, minor=%#",uuid, major, minor);
self.lbl_regionStatus.text = #"Status : Entered Region";
if(foundBeacon.proximity==CLProximityImmediate)
{
NSLog(#"Immediate");
//self.Lb_proxomity.text = #"Immediate";
}
else if (foundBeacon.proximity==CLProximityNear)
{
NSLog(#"Near");
//self.Lb_proxomity.text = #"Near";
}
else if(foundBeacon.proximity==CLProximityFar)
{
NSLog(#"Far");
//self.Lb_proxomity.text = #"Far";
}
else if(foundBeacon.proximity==CLProximityUnknown)
{
NSLog(#"Unknown");
//self.Lb_proxomity.text = #"Unknown";
}
float actualDistance = foundBeacon.accuracy/10;
NSLog(#"Distance = %f",actualDistance);
if(actualDistance >= 0.0)
{
self.lbl_distance.text = [NSString stringWithFormat:#"Distance : %.2f m",actualDistance];
}
//self.Lb_meter.text = [NSString stringWithFormat:#"%.2f",foundBeacon.accuracy];
//self.Lb_centimeter.text = [NSString stringWithFormat:#"%.2f",(foundBeacon.accuracy*100)];
//[self presentExhibitInfoWithMajorValue:foundBeacon.major.integerValue];
//Calling this method to display strength for distance between user and the pet
[self fn_showStrengthForDistanceBetweenUserAndPet:actualDistance];
}
#pragma mark - Check Background App Refresh status
-(BOOL)CanDeviceSupportAppBackgroundRefresh
{
// Override point for customization after application launch.
if ([[UIApplication sharedApplication] backgroundRefreshStatus] == UIBackgroundRefreshStatusAvailable) {
NSLog(#"Background updates are available for the app.");
return YES;
}else if([[UIApplication sharedApplication] backgroundRefreshStatus] == UIBackgroundRefreshStatusDenied)
{
NSLog(#"The user explicitly disabled background behavior for this app or for the whole system.");
return NO;
}else if([[UIApplication sharedApplication] backgroundRefreshStatus] == UIBackgroundRefreshStatusRestricted)
{
NSLog(#"Background updates are unavailable and the user cannot enable them again. For example, this status can occur when parental controls are in effect for the current user.");
return NO;
}
return NO;
}
#pragma mark - Check if monitoring region failed
- (void)locationManager:(CLLocationManager *)manager monitoringDidFailForRegion:(CLRegion *)region withError:(NSError *)error
{
NSLog(#"monitoringDidFailForRegion - error: %#", [error localizedDescription]);
}
- (void)locationManager:(CLLocationManager *)manager didDetermineState:(CLRegionState)state forRegion:(CLBeaconRegion *)region{
if (state == CLRegionStateInside) {
//Start Ranging
[manager startRangingBeaconsInRegion:region];
}
else{
//Stop Ranging
[manager stopRangingBeaconsInRegion:region];
}
}
#end
I suspect you are having authorization issues on your iPhone. Set a breakpoint or add NSLog statements to make sure this line is getting called:
[self.locationManager requestAlwaysAuthorization];
Do you get prompted? If not, uninstall and reinstall.
Also, check in setting that Bluetooth and Location services are enabled on the phone, and check settings on your app to see that location services are actually enabled for it.
You need to set one of
NSLocationAlwaysUsageDescription
or
NSLocationWhenInUseUsageDescription when requesting location updates (even with iBeacons).
If you don't, in iOS 8, this will fail silently.

Estimote iBeacons not detecting

i have recently purchased the estimote i have seen lots of demo but not able to detect the device.
Here is my code
- (void)viewDidLoad
{
[super viewDidLoad];
self.peripheralManager = [[CBPeripheralManager alloc] initWithDelegate:self
queue:nil
options:nil];
//Set location managaer delegate
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
NSUUID* uuid = [[NSUUID alloc] initWithUUIDString:#"B9407F30-F5F8-466E-AFF9-25556B57FE6D"];
// 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;
[self.locationManager startMonitoringForRegion:self.beaconRegion];
[self.locationManager startRangingBeaconsInRegion:self.beaconRegion];
// Do any additional setup after loading the view, typically from a nib.
}
// Delegate method returns Region state UNKNOWN!!!
-(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!!!");
[self.locationManager stopRangingBeaconsInRegion:self.beaconRegion];
break;
}
}
// Enter Region
-(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];
}
}
}
What i am missing? How can i change ProximityUUID.
Just add one more line to the bottom of your viewDidLoad method:
[self.locationManager startMonitoringBeaconsInRegion:self.beacon region];

How to get paired bluetooth devices

I want to create one application that show me paired devices in my app.(for example any device that paired me before detect and show me.)
also in the next time I want to send one NSString like "hello" to paired device.
I searching in google and I got so confused!!!
Please tell me first how to get paired device with my mobile and second how to send NSString value to them.
Here is an exemple for what you need :
You have to adapt it to match what u want. But you can see how it work ...
#implementation ViewController
{
CBPeripheralManager *_peripheralManager;
BOOL _isAdvertising;
}
- (void)_startAdvertising
{
NSUUID *estimoteUUID = [[NSUUID alloc] initWithUUIDString:#"B9407F30-F5F8-466E-AFF9-25556B57FE6D"];
CLBeaconRegion *region = [[CLBeaconRegion alloc] initWithProximityUUID:estimoteUUID
major:2
minor:1
identifier:#"SimEstimote"];
NSDictionary *beaconPeripheralData = [region peripheralDataWithMeasuredPower:nil];
[_peripheralManager startAdvertising:beaconPeripheralData];
}
- (void)_updateEmitterForDesiredState
{
if (_peripheralManager.state == CBPeripheralManagerStatePoweredOn)
{
// only issue commands when powered on
if (_isAdvertising)
{
if (!_peripheralManager.isAdvertising)
{
[self _startAdvertising];
}
}
else
{
if (_peripheralManager.isAdvertising)
{
[_peripheralManager stopAdvertising];
}
}
}
}
#pragma mark - CBPeripheralManagerDelegate
- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral
{
[self _updateEmitterForDesiredState];
}
#pragma mark - Actions
- (IBAction)advertisingSwitch:(UISwitch *)sender
{
_isAdvertising = sender.isOn;
[self _updateEmitterForDesiredState];
}
#end
This for monitoring :
#implementation AppDelegate
{
CLLocationManager *_locationManager;
BOOL _isInsideRegion; // flag to prevent duplicate sending of notification
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)options
{
// create a location manager
_locationManager = [[CLLocationManager alloc] init];
// set delegate, not the angle brackets
_locationManager.delegate = self;
NSUUID *estimoteUUID = [[NSUUID alloc] initWithUUIDString:#"B9407F30-F5F8-466E-AFF9-25556B57FE6D"];
CLBeaconRegion *region = [[CLBeaconRegion alloc] initWithProximityUUID:estimoteUUID
identifier:#"Estimote Range"];
// launch app when display is turned on and inside region
region.notifyEntryStateOnDisplay = YES;
if ([CLLocationManager isMonitoringAvailableForClass:[CLBeaconRegion class]])
{
[_locationManager startMonitoringForRegion:region];
// get status update right away for UI
[_locationManager requestStateForRegion:region];
}
else
{
NSLog(#"This device does not support monitoring beacon regions");
}
// Override point for customization after application launch.
return YES;
}
- (void)_sendEnterLocalNotification
{
if (!_isInsideRegion)
{
UILocalNotification *notice = [[UILocalNotification alloc] init];
notice.alertBody = #"Inside Estimote beacon region!";
notice.alertAction = #"Open";
[[UIApplication sharedApplication] scheduleLocalNotification:notice];
}
_isInsideRegion = YES;
}
- (void)_sendExitLocalNotification
{
if (_isInsideRegion)
{
UILocalNotification *notice = [[UILocalNotification alloc] init];
notice.alertBody = #"Left Estimote beacon region!";
notice.alertAction = #"Open";
[[UIApplication sharedApplication] scheduleLocalNotification:notice];
}
_isInsideRegion = NO;
}
- (void)_updateUIForState:(CLRegionState)state
{
ViewController *vc = (ViewController *)self.window.rootViewController;
if (state == CLRegionStateInside)
{
vc.label.text = #"Inside";
}
else if (state == CLRegionStateOutside)
{
vc.label.text = #"Outside";
}
else
{
vc.label.text = #"Unknown";
}
}
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager
didDetermineState:(CLRegionState)state forRegion:(CLRegion *)region
{
// always update UI
[self _updateUIForState:state];
if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive)
{
// don't send any notifications
return;
}
if (state == CLRegionStateInside)
{
[self _sendEnterLocalNotification];
}
else
{
[self _sendExitLocalNotification];
}
}
#end
You can have the complete description at this adress :
http://www.cocoanetics.com/2013/11/can-you-smell-the-ibeacon/

Resources