How To Use iBeacons in iOS 7 to Enhance Your Apps
Editor’s note: This week, we work with Chris Ching from Code With Chris to give you an introduction to iBeacons in iOS 7. Not only you’ll learn what iBeacon is, Chris will show you how to use iBeacons in your apps.
Surely you’ve heard of the nifty new feature in iOS 7 that lets your app gather location contextual information indoors where it can’t use GPS? If you haven’t, not to fear because we’re going to show you what it is and how you can use it in this article!
Beacon works over Bluetooth Low Energy (BLE) technology in your iPhone and as the name implies, it’s incredibly battery efficient. Going hand in hand with being low energy, it also has a short range of approximately 150 feet.
Real World Applications
The impact of having location sensitive information while indoors is already turning into real world applications. For example, Macy’s already has a pilot program underway where it has planted several beacons in different departments around the store. When a user passes by one of these departments and the companion app on their phone picks up the broadcast, it’ll open the app and display contextual information like promos, featured products and deals. Take a look at this short video to see iBeacons in action!
Our Demo
Similar to the Macy’s pilot program app, the sample app we’re building here today will demonstrate how to detect and handle a broadcast from a beacon. However, in order to have a beacon to handle, we have to first create another app to act as the beacon which will do nothing except broadcast a signal. By the end of the article, we’ll have two apps representing both sides of the communication.
Setup: The Broadcasting App
What exactly does the beacon broadcast? Well it’s a UUID that looks something like this:
1 |
C293726B-63BF-420A-9D79-92C71F67536A |
The beacon will continually broadcast this UUID and the receiver app will detect beacons with this same UUID.
Let’s get started by creating a new Single View Application in Xcode.
Click next and give the project a name and you can put “AppCoda” as the company and “com.appcoda” as the bundle identifier:
Next let’s add the images for the button that will start the broadcasting.
Go to your image asset library (images.xcassets) and in the asset listing, right click and select “New Image Set”.
Then rename the image set to “BroadcastButton”. When you select this image set, you’ll see that there are spots for you to add a 2x image and a 1x image.
Save these two button images onto your file system and then drag “[email protected]” into the 2x spot and “BroadcastBtn.png” into the 1x spot.
In Main.storyboard, we’re going to add a UIButton element so drag one onto your view from the Objects pane in the lower right hand corner.
Select the button in the storyboard and go into the attributes inspector to get rid of the title and change the image to the image set that we added.
Position your button in the middle of the view and your view should look like this
Now let’s add a UILabel element to the view so that we know when the app is broadcasting. Drag a UILabel element from the Objects pane onto your view.
Then go into the attributes and size inspector and change it to center alignment and width 200. Center it in your view and you should get something like this
Next, we’ll expose the UILabel to our ViewController object by hooking it up to an IBOutlet property. Let’s open up Assistant Editor (you can do so with the assistant editor button in the upper right corner of the Xcode interface).
Make sure that you’re looking at ViewController.h in the right pane and then hold “control” and click and drag a line from the UILabel to a space between the “@interface” and “@end” lines in the .h file.
When you release your mouse, you’ll see a pop up dialog. Give the property a name of “statusLabel”.
Your ViewController.h file will look like this:
1 2 3 4 5 |
@interface ViewController : UIViewController @property (strong, nonatomic) IBOutlet UILabel *statusLabel; @end |
Now let’s connect the broadcast button to a IBAction method handler. Stay in Assistant Editor but change the right pane to ViewController.m. Hold “control” and click and drag a line from the UIButton to a space between the “@implementation” and “@end” lines in the .m file. In the pop up dialog, give the method the name “buttonClicked”
Your ViewController.m file will have this method at the end now:
1 2 |
- (IBAction)buttonClicked:(id)sender { } |
Adding Required Frameworks
Before we can actually broadcast anything over Bluetooth, we need to add the appropriate frameworks to our project.
Go to your project settings and scroll to the bottom. Click the “+” button under “Linked Frameworks and Libraries” to add CoreBluetooth.framework and CoreLocation.framework.
Creating a UUID
Open up Launchpad on your Mac (or just go to the Applications folder) and open the Terminal app. In Launchpad, it may be in a folder called “Other” and the icon looks like this:
Once opened, you’ll have a window where you can type in “uuidgen” and it will output a UUID for you to use! Copy the generated UUID because we’re going to be broadcasting that!
Beacon Broadcasting
In ViewController.h let’s import the frameworks which we added earlier.
1 2 |
#import <CoreLocation/CoreLocation.h> #import <CoreBluetooth/CoreBluetooth.h> |
Next, let’s add 3 more properties that we’ll be using to broadcast. So in total, you’ll have 4 properties in your ViewController.h file.
1 2 3 4 |
@property (weak, nonatomic) IBOutlet UILabel *statusLabel; @property (strong, nonatomic) CLBeaconRegion *myBeaconRegion; @property (strong, nonatomic) NSDictionary *myBeaconData; @property (strong, nonatomic) CBPeripheralManager *peripheralManager; |
One more thing we have to do here is have the ViewController class conform to the “CBPeripheralManagerDelegate” protocol and we do that by adding this to the class declaration:
1 |
@interface ViewController : UIViewController<CBPeripheralManagerDelegate> |
Ok, now we’re done in the .h file, let’s go into the .m file.
In the viewDidLoad method, add the following code (substitute the UUID for the one you generated).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. // Create a NSUUID object NSUUID *uuid = [[NSUUID alloc] initWithUUIDString:@"A77A1B68-49A7-4DBF-914C-760D07FBB87B"]; // Initialize the Beacon Region self.myBeaconRegion = [[CLBeaconRegion alloc] initWithProximityUUID:uuid major:1 minor:1 identifier:@"com.appcoda.testregion"]; } |
In the code above, we’re creating a new NSUUID object by passing in the UUID that we want to broadcast.
Then we’re setting up a CLBeaconRegion and initializing it with that UUID, a major and minor number and an identifier.
The major and minor numbers are for you to identify your beacons if you have a whole bunch of them inside your location. In the Macy’s example above, each department may have a specific major number which identifies a group of beacons and inside that department, each beacon may have a specific minor number. So with both the major and minor, you’ll be able to identify exactly which beacon has been picked up.
Finally, the identifier is a unique id for that region.
In the buttonClicked method that we set up earlier, let’s add this code:
1 2 3 4 5 6 7 8 9 10 |
- (IBAction)buttonClicked:(id)sender { // Get the beacon data to advertise self.myBeaconData = [self.myBeaconRegion peripheralDataWithMeasuredPower:nil]; // Start the peripheral manager self.peripheralManager = [[CBPeripheralManager alloc] initWithDelegate:self queue:nil options:nil]; } |
In the code above, we’re calling the method “peripheralDataWithMeasuredPower:” method of the beacon region which will give us the beacon data that we will later use to broadcast.
The second line starts the peripheral manager and will start to monitor updates to the status of Bluetooth.
Now we have to handle the status update method to detect when Bluetooth is on and off. So add this delegate method which is required because our ViewController class conforms to the “CBPeripheralManagerDelegate” protocol.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
-(void)peripheralManagerDidUpdateState:(CBPeripheralManager*)peripheral { if (peripheral.state == CBPeripheralManagerStatePoweredOn) { // Bluetooth is on // Update our status label self.statusLabel.text = @"Broadcasting..."; // Start broadcasting [self.peripheralManager startAdvertising:self.myBeaconData]; } else if (peripheral.state == CBPeripheralManagerStatePoweredOff) { // Update our status label self.statusLabel.text = @"Stopped"; // Bluetooth isn't on. Stop broadcasting [self.peripheralManager stopAdvertising]; } else if (peripheral.state == CBPeripheralManagerStateUnsupported) { self.statusLabel.text = @"Unsupported"; } } |
The method above gets triggered whenever there is a change in the Bluetooth peripheral status. So in the method, we check what the current status is. If it’s on, we’ll update our label and call the “startAdvertising” method and pass it our beacon data to broadcast. Conversely, if the status is off, then we’ll stop advertising.
Now when you deploy the app to your device, turn on bluetooth and tap the button, it’ll be broadcasting your UUID! Let’s create the receiver app to detect and handle the broadcast!
Note: You won’t be able to broadcast via the simulator because it can’t use bluetooth. You’ll need to be enrolled in the Apple Developer program in order to be able to put this app on an actual device which supports BLE (iPhone 4S and up, iPad mini and iPad 3 and up)
Detecting Beacon Proximity
Let’s set up another Single View Application and this time, call it “BeaconReceiver”.
Go into the Main.storyboard and let’s keep it simple and add a single UILabel to the view that we’ll use to update the status when a beacon is detected. Drag a UILabel element from the Objects pane onto your view. Then click the UILabel and go into the attributes inspector to change the alignment to Center Align and change the width to 200.
You’ll end up with this:
Adding the CoreLocation Framework
The core location framework has been updated to support beacon detection and we need to add it to our project. Go to your project properties and click the “+” icon under “Linked Libraries and Frameworks”. Add CoreLocation.framework
Now just like we did before, let’s expose the UILabel as an IBOutlet property. Open up Assistant Editor and make sure ViewController.h is on the right hand pane. Then hold down “control” and click the UILabel and drag a line over to the right pane in between “@interface” and “@end”. When you let go, a pop up dialog will show up and you can name the property “statusLabel”.
1 2 3 4 5 |
@interface ViewController : UIViewController @property (weak, nonatomic) IBOutlet UILabel *statusLabel; @end |
Finally, go into ViewController.h and import the framework at the top and modify the class declaration to conform to the CLLocationManagerDelegate protocol because the protocol contains a delegate method that will let us know of newly detected beacons.
1 2 3 4 5 6 7 8 |
#import <UIKit/UIKit.h> #import <CoreLocation/CoreLocation.h> @interface ViewController : UIViewController<CLLocationManagerDelegate> @property (weak, nonatomic) IBOutlet UILabel *statusLabel; @end |
Detecting Beacons
We need to add two properties. One to keep track of the beacon region we’re trying to detect and the other to hold the location manager which will give us updates on beacons found so add this code to ViewController.h:
1 2 3 4 5 6 7 |
@interface ViewController : UIViewController<CLLocationManagerDelegate> @property (strong, nonatomic) CLBeaconRegion *myBeaconRegion; @property (strong, nonatomic) CLLocationManager *locationManager; @property (weak, nonatomic) IBOutlet UILabel *statusLabel; @end |
Now go into ViewController.m and in the “viewDidLoad” method, we’re going to initialize our locationManager and set ourselves as the delegate for it. We’re also going to start monitoring for the desired beacon so have that UUID handy!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. // Initialize location manager and set ourselves as the delegate self.locationManager = [[CLLocationManager alloc] init]; self.locationManager.delegate = self; // Create a NSUUID with the same UUID as the broadcasting beacon NSUUID *uuid = [[NSUUID alloc] initWithUUIDString:@"A77A1B68-49A7-4DBF-914C-760D07FBB87B"]; // Setup a new region with that UUID and same identifier as the broadcasting beacon self.myBeaconRegion = [[CLBeaconRegion alloc] initWithProximityUUID:uuid identifier:@"com.appcoda.testregion"]; // Tell location manager to start monitoring for the beacon region [self.locationManager startMonitoringForRegion:self.myBeaconRegion]; } |
Ok a lot is going on in the code above so let’s take it line by line.
In Line 7 and 8, we’re initializing locationManager to a new instance of CLLocationManager and then setting ourselves as its delegate so we can be notified of updates.
In line 11, we’re setting up a NSUUID object with the same UUID as the one that’s being broadcasted by the app we created earlier.
In line 14, we’re setting up the beacon region by passing in the UUID we want to look for as well as the region identifier of the region that’s being broadcasted.
And finally in line 18, we’re passing the region into the location manager to monitor for us.
Next we’re going to need to implement some delegate methods that will be called when the region is detected.
First add these methods to your ViewController.m:
1 2 3 4 5 6 7 8 9 10 |
- (void)locationManager:(CLLocationManager*)manager didEnterRegion:(CLRegion*)region { [self.locationManager startRangingBeaconsInRegion:self.beaconRegion]; } -(void)locationManager:(CLLocationManager*)manager didExitRegion:(CLRegion*)region { [self.locationManager stopRangingBeaconsInRegion:self.beaconRegion]; self.beaconFoundLabel.text = @"No"; } |
The code above implements two methods that get triggered when the device enters a region or leaves a region. When a region is entered, we tell locationManager to start looking for beacons in the region.
Now implement this method below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
-(void)locationManager:(CLLocationManager*)manager didRangeBeacons:(NSArray*)beacons inRegion:(CLBeaconRegion*)region { // Beacon found! self.statusLabel.text = @"Beacon found!"; CLBeacon *foundBeacon = [beacons firstObject]; // You can retrieve the beacon data from its properties //NSString *uuid = foundBeacon.proximityUUID.UUIDString; //NSString *major = [NSString stringWithFormat:@"%@", foundBeacon.major]; //NSString *minor = [NSString stringWithFormat:@"%@", foundBeacon.minor]; } |
This method will get fired when one or more beacons are detected. In the code above you can see how we could get the UUID, major and minor data from the beacon. Furthermore, although we don’t implement it above, you can loop through the beacons array and determine which one is the closest by checking the proximity property of the beacon.
Running The Demo
If you’ve got two devices and you’ve paid to enrol in the Apple iOS Developer program, you can test the communication out. Launch the beacon app and tap the “Broadcast” button and wait for the “Broadcasting…” message to appear.
Launch the receiver app and carry it far away from the broadcasting beacon and then walk towards it to simulate entering the region.
Summary
If you don’t have multiple devices, you can still build some cool applications by buying BLE beacons and placing them around your house. Estimote makes such beacons and you get three for $99.
So I hope you can see how powerful and applicable iBeacons are and I hope this demo has sparked your imagination for some real world possibilities too! For your complete reference, you can download the Xcode project of the demo app from here.
I’d love to hear your thoughts in the comments below and if you learned something new, please use the social buttons to share this with your friends and colleagues!
This post is contributed by Chris Ching from Code With Chris. Chris has taught iOS programming to many beginners through his site and YouTube channel and has recently launched a video course: How To Create An App.
Comments
dariux
AuthorI just say, “Esta super chingon el tutorial” in other words congratulations for this great tut!
Chris Ching
AuthorThanks Dariux! Appreciate it and thanks for reading! 🙂
PghTV
AuthorThanks, Chris – good stuff. I ordered the Estimote a week ago and was just about ready to start playing around with iBeacon code. Very timely! I’m hoping to use the relative range reporting to do some GPS-like navigation indoors.
Hugh Mbaezue
AuthorWow Perfect timing Chris. I just landed a project that has to do with iBeacons. Working with Estimote to be exact! Thank you so much for this tutorial, just what I needed…
Ly4S
AuthoriBeacons was one of the things I got really excited about during WWDC. I’ve done some experimenting on my own but this is an excellent tutorial and really solidified my learning. Now my enthusiasm has been reinvigorated, thanks!
Carl
AuthorHello Chris! Thanks a lot for your tutorial, it helped me a lot with my project!
There’s a small problem: my app (the receiver) is not always firing up the method “didRangeBeacons” when a beacon is found. It sometimes does but rarely.
Thanks in advance!
Joel
AuthorGood tutorial, found some typos:
– (void)locationManager:(CLLocationManager*)manager didEnterRegion:(CLRegion*)region
{
[self.locationManager startRangingBeaconsInRegion:self.beaconRegion];
}
-(void)locationManager:(CLLocationManager*)manager didExitRegion:(CLRegion*)region
{
[self.locationManager stopRangingBeaconsInRegion:self.beaconRegion];
self.beaconFoundLabel.text = @”No”;
}
Should be:
– (void)locationManager:(CLLocationManager*)manager didEnterRegion:(CLRegion*)region
{
[self.locationManager startRangingBeaconsInRegion:self.myBeaconRegion];
}
-(void)locationManager:(CLLocationManager*)manager didExitRegion:(CLRegion*)region
{
[self.locationManager stopRangingBeaconsInRegion:self.myBeaconRegion];
self.statusLabel.text = @”No”;
}
Chris Ching
AuthorGood eye, thanks for letting me know Joel!
Jack
AuthorCheers for the tutorial, very helpful!! just wondering if it is possible to combine a receiver and an iBeacon into one app?
Thanks!
Jack
Chris Ching
AuthorHey Jack, it’s possible to put it into the same app and let the user select whether it should be a receiver or a broadcaster on launch!
Adrienne
AuthorTwo things –
First: You should call [self.locationManager requestStateForRegion:self.beaconRegion] after calling [self.locationManager startMonitoringForRegion:self.beaconRegion]. This seems to force it to check if it’s already IN the region.
Second: You MUST have “Background App Refresh” enabled for region monitoring to work! I tried this example and it just wouldn’t work for me. I checked the value of [CLLocationManager isMonitoringAvailableForClass:[self.beaconRegion class]] and of [CLLocationManager authorizationStatus] and both were fine, so I was stumped for a while. Finally I found the “Region Monitoring” section of Apple’s “Location and Maps Programming Guide” and discovered that this error can occur if “Background App Refresh” is disabled on the device. Once I enabled it, it worked fine.
Here’s my code for checking each of these values:
NSArray *locationServicesAuthStatuses = @[@”Not determined”,@”Restricted”,@”Denied”,@”Authorized”];
NSArray *backgroundRefreshAuthStatuses = @[@”Restricted”,@”Denied”,@”Available”];
BOOL monitoringAvailable = [CLLocationManager isMonitoringAvailableForClass:[self.beaconRegion class]];
NSLog(@”Monitoring available: %@”, [NSNumber numberWithBool:monitoringAvailable]);
int lsAuth = (int)[CLLocationManager authorizationStatus];
NSLog(@”Location services authorization status: %@”, [locationServicesAuthStatuses objectAtIndex:lsAuth]);
int brAuth = (int)[[UIApplication sharedApplication] backgroundRefreshStatus];
NSLog(@”Background refresh authorization status: %@”, [backgroundRefreshAuthStatuses objectAtIndex:brAuth]);
Chris Ching
AuthorThanks Adrienne for taking the time to comment and help everyone out!
I’ll get into contact w/ Simon to see if i can amend the article.
Thampuran
AuthorThanks Chris for the clear tutorial. And thank you Adrienne 🙂
I am attaching an image for those who are searching for how to set background-app refresh in iOS devices (because while reading I was not aware of this, and this may be useful for someone else too ) 😉
Thampuran
Authorhttp://support.apple.com/kb/ht4211
Rajesh Ghosh
AuthorHi Adrienne,
I tried with this updated code for the background App beacon detection and emitter. But its not working. If your have successfully implemented this features can you please share the full application.
Many thanks in Advance
Jay Santos
AuthorThis line of code is missing which is included in the sample app that can be downloaded:
// 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;
}
That line of code should be after this line of code:
[self.locationManager startMonitoringForRegion:self.myBeaconRegion];
Chris Ching
AuthorHey Jay, thanks for pointing it out! Not sure if the sample code was modified already but I found that line above the IF statement in the sample code and I can’t remember if i added that 😛
It’d probably be best put in a ELSE clause while we’re at it.
Thanks for reading and taking the time to comment!
Brian McGuire
AuthorNice tutorial. However I am running into some challenges. I was able to write, compile and push the individual apps to two different iOS Dev iPhones (4s & 5s). I am able to start both apps successfully. I am able to click “Broadcast” and start the broadcasting process, however I am not getting any responses on the receiver app. I checked to make sure I had the same UUID’s thinking it was that. Any ideas? Thanks.
Marvi
AuthorI’m running into the same issue. Glad to receive some help
Chris Ching
AuthorHello Marvi, unfortunately with the implementation I did in the article, if you start the receiver when it’s already in the beacon range, it’s not going to fire. Just checking that you’re walking far away from the beacon and then walking back into range to get it to fire?
Also Adrienne, a commenter below, mentioned that you need to have “Background App Refresh” enabled on the device for it to work.
Give that a try!
Nagesh
AuthorVery good tutorial. I have downloaded the your app and ran it on my iPhone 4 its saying “Unsupported” please help
Nagesh
AuthorThe Beacon app is not listed in Bluetooth sharing, how can I add it.
awebb
AuthorUnfortunately the iPhone 4 does not support BLE
Raptor
AuthorBluetooth on iPhone 4 does not support Bluetooth LE, which is required for iBeacon.
joemccann
AuthorExcellent tutorial.
Chris Ching
AuthorThanks for reading joe!
Steven
AuthorHey how do you make the BroadcastButton Image ?
With PS ?
Can you send me the Project pls :).
Thank You !
Tom
AuthorYes this i want to know,too!
Chris Ching
AuthorHey Tom, you can download the Xcode project in the link under the “Summary” section.. button image was made in PS!
Chris Ching
AuthorHey Steven! You can download the project in the link under the “Summary” section. Yup was made in PS 🙂
Steven
AuthorTank you for the Answer!
I mean with Project ,the PS Project 😀 for the Buttons.
They are really cool 🙂 ..so can you send me maybe the “PS” Project please :).
Thank you !
Chris Ching
Authorno problem! 🙂 Can you get in contact with me through the contact link on my site? Then i can email it as an attachment for you. Thanks.
Steven
AuthorDone 🙂 Subject PS ButtonImage
Gunnar Forsgren
AuthorThanks, one of my first ventures into iOS coding and this was a good intro to discovering some
less intuitive xcode steps in development.
Gunnar Forsgren
AuthorWorth mentioning the beacon emitted by this example transmit app is also detected by Android BLE scanning apps. In that scenario the iBeacon app outlined here demonstrates the potential of how quickly a BLE device can detected after it begins broadcasting its beacon.
Chris
AuthorHi Chris, Great piece of work!
I have a couple of questions, I have purchased a beacon, I have the UUID and wish to only use the second part of your code (the receiver app) to try and link it to a real beacon, I am a bit stuck with the Minor and Major bit of the code.
Looking at the receiver code, this bit:
// Setup a new region with that UUID and same identifier as the broadcasting beacon
self.myBeaconRegion = [[CLBeaconRegion alloc] initWithProximityUUID:uuid
identifier:@”com.appcoda.testregion”];
Which refers to:
// Initialize the Beacon Region
self.myBeaconRegion = [[CLBeaconRegion alloc] initWithProximityUUID:uuid
major:1
minor:1
identifier:@”com.appcoda.testregion”];
In the first app, Obviously I only have the UUID, I don’t have the identifier, so what would I change in the code on the receiver app to just look for the UUID of the beacon I have rather than the beacon app which I haven’t made? …if that makes sense?
Thanks,
Chris
Ed
AuthorHey Chris,
I am in the same boat you were with this question. Did you ever figure it out?
Thanks,
Ed
Kevin Doherty
AuthorI am in the same boat as well? Did either of you happen to figure it out?
liangj
AuthorIs There “How to use ibeacons in iSO7 with triangulation” example for an app?
James
AuthorMy receiver doesn’t seem to my beacon even if I go far out of range (30-40 m) and come back. “Background App Refresh”is enabled on my device. I tried the suggestion Adriene below made, adding [self.locationManager requestStateForRegion:self.myBeaconRegion].
Any more suggestions?
文武 吴
AuthorHI-
I want to obtain the accurately distance between the iBeacon and the divece.
Can someone help me ?
thanks a lot!
Mustafa
AuthorFirst of all, thanks Chris,
My question is can uuid program as dynamic?
if it possible that uuid can be changed according to time dinamicly (for example per 30 minutes in predefined uuid range)
frafri
AuthorThis tutorial rocks!Thank you so much !
Lucifer
AuthorI have a question, why does not it alert or notify when the app is not running in the background or hard closed. Or how? please let me know. Thanks.
vanessa
AuthorHi Sone of Lucifer:
Did anyone get back to you on how the app can work in the background?
Seb Hareng
AuthorGreat tutorial! Thanks Chris for creating it.
I wanted to mention an issue I found a fix for. In some cases the startMonitoringForRegion didn’t trigger for me. It got fixed after I added the following code:
Added this line in viewDidLoad:
self.myBeaconRegion.notifyEntryStateOnDisplay = YES;
Added this method:
– (void)locationManager:(CLLocationManager *)manager didDetermineState:(CLRegionState)state forRegion:(CLRegion *)region { if (state == CLRegionStateInside){ NSLog(@”is in target region”); [self.locationManager startRangingBeaconsInRegion:self.myBeaconRegion]; }else{ NSLog(@”is out of target region”); }
}
Hope it helps someone
Lasse
AuthorI had a problem with my reciever not recieving anything. Turns out there is a bluetooth stack issue you can run into. After a restart of my phone the beacon was detected straight away.
Thank you Chris for taking you time to share this, it was a welcomed speedy intro into iBeacons.
Rohith Kumar
AuthorHy Nice Tutorial !!!
IS it possible to scan multiple regions within the same shop or building?? Please do help me out on same !!Thanks in Advance
onmir
Authorinstead of displaying a local notification is it possible to get data from webserver, let’s say more information about the beacon, while the app is in background?
Nick
AuthorGreat tutorial! If anyone wants to add the ability to only alert when the beacon is within a certain proximity (far, near, immediate), here’s how to do it: http://ibeaconmodules.us/blogs/news/14279747-tutorial-getting-started-with-ibeacon-app-development
Hope this helps!
Deepak
AuthorCan you share the link again. Above link in not working.
Hardik
AuthorHi Can this works even when the app is not in background i mean app is completely closed.
mr.cool
AuthorIs it possible to share the data between two iPhone devices through the sample which you developed ?
Minsara
AuthorThanks alot for the great tutorial
Diego
AuthorHi, the tutorial is great, but I’m afraid it’s not working for me. I have a beacon which is being located by another app ( Locate iBeacons by Radius Networks ) which is not detected by this app.
Also I checked the permissions and I get this:
2014-09-08 15:54:37.285 BeaconReceiver[212:5424] Monitoring available: 0
2014-09-08 15:54:37.288 BeaconReceiver[212:5424] Location services authorization status: Not determined
2014-09-08 15:54:37.296 BeaconReceiver[212:5424] Background refresh authorization status: Available
So, I think this stuff may be the problem. Any clue?
Thanks!
Diego
AuthorWell, I’ll answer myself. The issue is related to iOS8 new location permissions. It’s not all clear to me now, but it seems all this is needed:
1. Edit Info.plist file and add these two keys ( changing the description of course … or not 🙂 ):
NSLocationWhenInUseUsageDescription
The spirit of stack overflow is coders helping coders
NSLocationAlwaysUsageDescription
I have learned more on stack overflow than anything else
2. In viewdidload:
[self.locationManager requestWhenInUseAuthorization];
[self.locationManager requestAlwaysAuthorization];
More info in this thread:
http://stackoverflow.com/questions/24062509/ios-8-location-services-not-working
Bruno
AuthorHey Chris! Great work!
I just have a question for you, will the app keep monitoring beacons on the background. What do I have to do if I want my app to send a push notification when it detects a beacon, even if the app is not running.
THanks!
Reddy Basha
AuthoriBeacon not detecting in iOS 8 it was working fine in iOS7. May i know what is the issue
David Winegar
AuthorFor those of you interested in making iBeacon apps but want to do it the easy way, or don’t have any programming skills, I have created a course on Udemy.com that helps you learn how to make a real iBeacon app that you can submit to the app store with no coding. I show you how to set up iBeacons and how to trigger actions in the app. If you can click – you can make an iBeacon mobile app with my course. https://www.udemy.com/ibeacons
Fabio Carbone
AuthorWith this implementation, as the author say, if you start the receiver when it’s already in the beacon range, it’s not going to fire. If you want find an ibeacon you need to walk far away from its region, and then walk back into range.
How can I modify this code to find a beacon that it is in range when I lunch the app?
Apb
AuthorHow can I modify this code to find a beacon that it is in range when I lunch the app?
feizal
Authoris it posibble to name or tag the receiver, and then make the broadcaster app knows the receiver name?
Jack
AuthorI am not understand how to perform this task.
Can anyone help me?
Raptor
AuthorGreat tutorial, but doesn’t work on iOS 8.
didChangeAuthorizationStatus: Authorized When In Use
monitoringDidFailForRegion with region : The operation couldn’t be completed. (kCLErrorDomain error 4.)
which is an Access Denied error.
More details in this related Stack Overflow question:
http://stackoverflow.com/questions/27897475/ibeacon-settings-of-clbeaconregion-identifier
Shashank Mishra
AuthorThanks for tutorials I have some problem Please let me to solve
i am using ble peripheral tag after scanning i found identifier and name .
when i click on any cell the desire peripheral are connected ..
and button in peripheral tag will detect and didUpdateValueForCharacteristic method are called on button click.
but when we are moving to another screen the button will not detect and peripheral will disconnect ..
I want when the peripheral are connect one time they always to be connected until app are not suspended ..
thanks in advance …
Jeffery Leo
AuthorGot this tutorial for iOS 8?
pradeep
AuthorYou need to add the below two lines in the plist of receiver
NSLocationWhenInUseUsageDescription
NSLocationAlwaysUsageDescription
and these codes in viewdidload of receiver
if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
[self.locationManager requestWhenInUseAuthorization];
}
[self.locationManager requestWhenInUseAuthorization];
[self.locationManager requestAlwaysAuthorization];
Hope this helps
Max
AuthorIs there a swift tutorial? Or could someone translate this thanks!
Abdulsamad Shahid
AuthorHi Chris,
Your tutorial is really nice and I need to use iBeacon for the checkout system for the devices in my office is there any way that I can keep getting updates of -(void)locationManager:(CLLocationManager *)manager didRangeBeacons:(NSArray *)beacons inRegion: event even if the app is killed or running in the background.
Apb
AuthorHi, i happened to work on beacons and this seemed to be a good example. But I’m stuck in a part where i can modify this code to find a beacon that it is in range when I launch the app?
Is it possible?
Hung Dat
AuthorI get a trouble that when i test in real device sometimes it cant detect ibeacon. But when i use ibeacon detecting tool it is ok. It is not far i think normal device can detect.
Deepak
AuthorHello Chris,
the download link is broken. Can you please update the url to download or send me the project please.
Thanks,
osvin solution
AuthorHey
Really Impressive.
Pushpendra Khandelwal
AuthorHey:
I have created beacon using the first part. On Click on button, I get status as “powerOff”.
Can anyone help me.
Thanks in advance
SRK
AuthorHi,
Monitoring for Beacon Region Will Call after terminate our application?