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.
Related
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.
I have a MapViewController that imports SWRevealViewController and I honestly didn't code this lines below. I tried to run the app but unfortunately the map is not showing the current location and even the location service does not get turn on the phone even the app is granted permission to access GPS. Since i'm not a expect in iOS development I need someone to look the code and explain what is missing in this code. I looked at similar question but they seem straight forward even for someone learning objective-c. The problem with this code i assume is the SWRevealViewController imported here, which I think is a library or something i don't know.
#import "MapViewController.h"
#import "SWRevealViewController.h"
// New York
#define NY_LATITUDE 40.754445
#define NY_LONGITUDE -73.977364
// Span and distance
#define SPAN_VALUE 1.0f
#define DISTANCE 500
#interface MapViewController ()
- (void)startLocationServices;
- (void)stopLocationServices;
#end
#implementation MapViewController
#synthesize locationManager;
#synthesize gpsDisplay;
#synthesize mapk;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (IBAction)sendRequest:(id)sender {
[self alertStatus:#"An assistance request has been sent, you will be contacted shortly." :#"Send assistance request" :0];
[self performSegueWithIdentifier:#"sendRequest" sender:nil];
}
- (void) alertStatus:(NSString *)msg :(NSString *)title :(int) tag
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
message:msg
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil, nil];
alertView.tag = tag;
[alertView show];
}
-(void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex: (NSInteger)buttonIndex
{
if(buttonIndex==0)
{
//NSLog(#"OK Clicked");
// [self alertStatus:#"An assistance request has been sent, you will be contacted shortly. " :#"I just had an accident" :0];
// [self performSegueWithIdentifier:#"checkProgress" sender:nil];
}}
- (void)viewDidLoad
{
[super viewDidLoad];
[self startLocationServices];
if ([CLLocationManager locationServicesEnabled]) {
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
[self.locationManager startUpdatingLocation];
} else {
NSLog(#"Location services are not enabled");
}
// Set a timer to stop the Location services
//[NSTimer scheduledTimerWithTimeInterval:100.0 target:self selector:#selector(stopLocationServices) userInfo:nil repeats:NO];
_sidebarButton.tintColor = [UIColor colorWithWhite:0.1f alpha:0.9f];
// 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];
// CLLocationManager *cllocationManager = [[CLLocationManager alloc] init];
// cllocationManager.delegate = self;
// cllocationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
// cllocationManager.distanceFilter = 20.0f;
//
// if ([CLLocationManager locationServicesEnabled])
// {
// [cllocationManager startUpdatingLocation];
// }
// else
// {
// UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Turn On Location Services to find your location"
// message:nil delegate:nil
// cancelButtonTitle:#"OK"
// otherButtonTitles:nil];
// [alert show];
// // [alert release];
// }
}
- (IBAction)mapChanger:(id)sender {
switch (((UISegmentedControl *) sender).selectedSegmentIndex) {
case 0:
self.mapk.mapType = MKMapTypeStandard;
break;
case 1:
self.mapk.mapType = MKMapTypeSatellite;
break;
case 2:
self.mapk.mapType = MKMapTypeHybrid;
break;
default:
break;
}
}
- (void)startLocationServices
{
// create the Location Manager
if (self.locationManager == nil) {
self.locationManager = [CLLocationManager new];
}
// settings
[self.locationManager setDelegate:self];
[self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
[self.locationManager setDistanceFilter:kCLDistanceFilterNone];
// start services
[self.locationManager startUpdatingLocation];
self.gpsDisplay.text = #"Location Service started.";
}
- (void)stopLocationServices
{
// stop services
[self.locationManager stopUpdatingLocation];
[self.locationManager setDelegate:nil];
self.gpsDisplay.text = #"Location Services stopped.";
}
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
CLLocationCoordinate2D loc = [userLocation coordinate];
// CLLocationDistance in meters (1 meter = 3.3 feet)
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(loc, DISTANCE, DISTANCE);
[mapView setRegion:region animated:YES];
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation {
NSString *coords =#"lat";
coords = [coords stringByAppendingString:[NSString stringWithFormat:#"%f", newLocation.coordinate.latitude]];
coords = [coords stringByAppendingString:#"lon"];
coords = [coords stringByAppendingString:[NSString stringWithFormat:#"%f", newLocation.coordinate.longitude]];
self.gpsDisplay.text = coords;
MKCoordinateRegion region;
region.center.latitude = newLocation.coordinate.latitude;
region.center.longitude = newLocation.coordinate.longitude;
region.span.latitudeDelta = SPAN_VALUE;
region.span.longitudeDelta = SPAN_VALUE;
[self.mapk setRegion:region animated:YES];
}
- (void)viewDidUnload {
//[self setUpdates:nil];
[super viewDidUnload];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
In addition to the previous answer, note that you have to specify the reason for accessing the user's location information adding the relative key (NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription) to your project's Info.plist
for example:
<key>NSLocationWhenInUseUsageDescription</key>
<string>Location is required to find out jobs around you are</string>
On iOS 8, they changed how you ask for location permission. Instead of just being able to call startUpdatingLocation you need to now call either requestWhenInUseAuthorization or requestAlwaysAuthorization.
i'm developing an iOS application and i'm using beacons.
I've a problem. I'm at the beginning of the development, so I only have my appdelegate. In appdelegate.m I have initialized like so
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
NSUUID *uuid = [[NSUUID alloc] initWithUUIDString:#"8AEFB031-6C32-486F-825B-E26FA193487D"];
CLBeaconRegion *region = [[CLBeaconRegion alloc] initWithProximityUUID:uuid
identifier:#"Region"];
if ([CLLocationManager isMonitoringAvailableForClass:[CLBeaconRegion class]])
{
NSLog(#"I'm looking for a beacon");
[self.locationManager startRangingBeaconsInRegion:region];
} else {
NSLog(#"Device doesn't support beacons ranging");
}
return YES;
}
and then I wrote two delegate methods
- (void) locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region {
NSLog(#"EXIT");
}
- (void) locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region {
NSLog(#"ENTER");
}
but they never get called!!! What's the problem here?
you RANGE but you never MONITOR the regions.
Ranging for beacons will only call: locationManager:didRangeBeacons:inRegion:
The methods enterRegion/exitRegion you want are for monitoring only. So call:
- (void)startMonitoringForRegion:(CLRegion *)region
I don't know why there are not calling but this is how we can handle beacons...
- (void)createBeaconRegion
{
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
NSUUID *uuid = [[NSUUID alloc] initWithUUIDString:#"8AEFB031-6C32-486F-825B-E26FA193487D"];
CLBeaconRegion *region = [[CLBeaconRegion alloc] initWithProximityUUID:uuid
identifier:#"Region"];
if ([CLLocationManager isMonitoringAvailableForClass:[CLBeaconRegion class]])
{
NSLog(#"I'm looking for a beacon");
[self.locationManager startRangingBeaconsInRegion:region];
} else {
NSLog(#"Device doesn't support beacons ranging");
}
}
- (void)turnOnRanging
{
NSLog(#"Turning on ranging...");
if (![CLLocationManager isRangingAvailable]) {
NSLog(#"Couldn't turn on ranging: Ranging is not available.");
self.rangingSwitch.on = NO;
return;
}
if (self.locationManager.rangedRegions.count > 0) {
NSLog(#"Didn't turn on ranging: Ranging already on.");
return;
}
[self createBeaconRegion];
[self.locationManager startRangingBeaconsInRegion:self.beaconRegion];
NSLog(#"Ranging turned on for region: %#.", self.beaconRegion);
}
- (void)startRangingForBeacons
{
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
self.detectedBeacons = [NSArray array];
[self turnOnRanging];
}
- (void)stopRangingForBeacons
{
if (self.locationManager.rangedRegions.count == 0) {
NSLog(#"Didn't turn off ranging: Ranging already off.");
return;
}
[self.locationManager stopRangingBeaconsInRegion:self.beaconRegion];
NSLog(#"Turned off ranging.");
}
You can refer the entire sample project using below link
https://github.com/nicktoumpelis/HiBeacons
That uses to display Beacons..
Hope it helps you....!
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/
I have location Manager. User can create tasks and pick distinction location. When user come to location - I show local notification. It works for one task. When I have more that one task some strange appear: I receive many notifications. I receive all scheduled notifications.
Question: how can I manage location Manager and push local notifications for different regions? Example: I have three regions - one in Moscow, one in London and one in New York. So, when user come to Moscow I want see only one notification (#"Notification 1"). When in London - notification 2. When in New York - notification 3.
Here my code:
//
// AddTaskViewController.m
// TaskManager
//
// Created by Vladyslav Semenchenko on 2/10/14.
// Copyright (c) 2014 Vladyslav Semenchenko. All rights reserved.
//
#import "AddTaskViewController.h"
#interface AddTaskViewController ()
#end
#implementation AddTaskViewController
#pragma mark - Defaul View life cycle methods
- (void)viewDidLoad
{
[super viewDidLoad];
// Positioning user location to center of mapView
userRegionPosition = MKCoordinateRegionMakeWithDistance([self.mapView userLocation].coordinate, 800, 800);
[self.mapView setRegion:[self.mapView regionThatFits:userRegionPosition] animated:YES];
// Set up delegates
self.textField.delegate = self;
self.mapView.delegate = self;
[self addGestureRecogniserToMapView];
// Add Location Manager
self.locationManager = [[CLLocationManager alloc] init];
[self.locationManager stopMonitoringSignificantLocationChanges];
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationManager.delegate = self;
NSLog(#"Monitored regions: %#", self.locationManager.monitoredRegions);
}
-(void)viewDidAppear:(BOOL)animated
{
// Positioning user location to center of mapView
userRegionPosition = MKCoordinateRegionMakeWithDistance([self.mapView userLocation].coordinate, 800, 800);
[self.mapView setRegion:[self.mapView regionThatFits:userRegionPosition] animated:YES];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if([segue.identifier isEqualToString:#"createTask"])
{
NSDictionary *newTask = [[NSDictionary alloc] initWithObjectsAndKeys:[self.textField text], #"Task text", nil];
[TasksIO addTasksToFile:newTask];
// Add Location Manager
if (self.enableLocationMonitoring.isOn){
taskRegion = [[CLCircularRegion alloc] initWithCenter:taskPlace.coordinate radius:1 identifier:[self.textField text]];
[self.locationManager startMonitoringForRegion:taskRegion];
}
}
}
#pragma mark - MapView methods
- (void)addGestureRecogniserToMapView{
UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc]
initWithTarget:self action:#selector(addPinToMap:)];
lpgr.minimumPressDuration = 0.5; //
[self.mapView addGestureRecognizer:lpgr];
}
- (void)addPinToMap:(UIGestureRecognizer *)gestureRecognizer
{
if (gestureRecognizer.state != UIGestureRecognizerStateBegan)
return;
CGPoint touchPoint = [gestureRecognizer locationInView:self.mapView];
CLLocationCoordinate2D touchMapCoordinate =
[self.mapView convertPoint:touchPoint toCoordinateFromView:self.mapView];
// Add annotation
NSArray *existingAnnotations = self.mapView.annotations;
[self.mapView removeAnnotations:existingAnnotations];
taskPlace = [[MKPointAnnotation alloc]init];
taskPlace.coordinate = touchMapCoordinate;
taskPlace.title = [self.textField text];
longitude = taskPlace.coordinate.longitude;
latitude = taskPlace.coordinate.latitude;
[self.mapView addAnnotation:taskPlace];
}
#pragma mark - TextField delegate methods
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
if (textField == self.textField) {
[textField resignFirstResponder];
}
return NO;
}
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager
didDetermineState:(CLRegionState)state forRegion:(CLRegion *)region
{
if(state == CLRegionStateInside)
{
UILocalNotification* localNotificationInside = [[UILocalNotification alloc] init];
localNotificationInside.fireDate = [NSDate date];
localNotificationInside.alertBody = #"It's time to do some work here!";
localNotificationInside.alertAction = #"Open App to view tasks..";
localNotificationInside.soundName = UILocalNotificationDefaultSoundName;
localNotificationInside.timeZone = [NSTimeZone defaultTimeZone];
localNotificationInside.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber] + 1;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotificationInside];
}
else if(state == CLRegionStateOutside)
{
}
else{
}
}
- (void)locationManager:(CLLocationManager *)manager didStartMonitoringForRegion:(CLRegion *)region
{
}
- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region
{
/*UILocalNotification* localNotificationInside = [[UILocalNotification alloc] init];
localNotificationInside.fireDate = [NSDate date];
//localNotificationInside.alertBody = #"It's time to do some work here!";
localNotificationInside.alertBody = self.textField.text;
localNotificationInside.alertAction = #"Open App to view tasks..";
localNotificationInside.soundName = UILocalNotificationDefaultSoundName;
localNotificationInside.timeZone = [NSTimeZone defaultTimeZone];
localNotificationInside.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber] + 1;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotificationInside];*/
}
#pragma mark - Helpers
-(void) showMessage:(NSString *) message
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Debug info"
message:message
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:Nil, nil];
alertView.alertViewStyle = UIAlertViewStyleDefault;
[alertView show];
}
- (IBAction)clearMonitoredLocations:(id)sender {
for (CLRegion *monitored in [self.locationManager monitoredRegions])
[self.locationManager stopMonitoringForRegion:monitored];
}
#end
Each CLRegion you add to monitor has an identifier, you can use this to identify which region is entered.