2015-02-25 4 views
0

Привет, у меня есть код, который отлично работает на iPod touch 5, но тот же код не работает на iPhone 6, я сделал исследование по той же проблеме, но я не нашел ничего полезного. оба устройства имеют новейшую iOS.Невозможно обнаружить ibeacon на iphone 6

Оба устройства имеют 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 
+0

Что именно происходит? Делегаты вообще не звонят? Пустой список маяков в делегате didRange? Не могли бы вы дважды проверить, имеет ли приложение «всегда» разрешение на использование служб определения местоположения? – heypiotr

+0

делегатов не вызывались –

+0

только это будет вызываться didChangeAuthorizationStatus никто не снизу didEnterRegion didExitRegion didDetermineState –

ответ

2

Я подозреваю, что у вас возникли проблемы авторизации на вашем iPhone. Установить точку останова или добавить заявления NSLog, чтобы убедиться, что эта линия вызывалась:

[self.locationManager requestAlwaysAuthorization]; 

ли вы получите запрос? Если нет, удалите и переустановите.

Кроме того, проверьте настройки Bluetooth и служб определения местоположения на телефоне и проверьте настройки своего приложения, чтобы увидеть, что на самом деле эти службы разрешены.

+0

да я получаю разрешение на приглашение –

+0

то, что вы предложили все я уже сделал, снова сделать, чтобы убедиться, что –

+0

он извините, я пропустил Bluetooth, bluetooth не был включен. глупая ошибка –

0

Вам необходимо установить один из

NSLocationAlwaysUsageDescription или NSLocationWhenInUseUsageDescription при запросе обновлений местоположения (даже с iBeacons).

Если вы этого не сделаете, то в iOS 8 это не будет работать тихо.

+0

Я сделал это, вот почему он работает на iPod 5 iOS 8 –

Смежные вопросы