Ios iBeacon设备重启后的监控/测距

Ios iBeacon设备重启后的监控/测距,ios,objective-c,core-location,ibeacon,Ios,Objective C,Core Location,Ibeacon,我用IBeacon构建了一个简单的ios应用程序,当应用程序位于前台或后台时,它可以正常工作,但在重新启动手机后,我的应用程序停止接收CoreLocation代理回调。这是我的AppDelegate.m代码 #import "AppDelegate.h" #import <CoreLocation/CoreLocation.h> #import "ViewController.h" @interface AppDelegate () @end @implementation A

我用IBeacon构建了一个简单的ios应用程序,当应用程序位于前台或后台时,它可以正常工作,但在重新启动手机后,我的应用程序停止接收CoreLocation代理回调。这是我的AppDelegate.m代码

#import "AppDelegate.h"
#import <CoreLocation/CoreLocation.h>
#import "ViewController.h"

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

   if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)]) {
        [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeSound
                                                                                                              categories:nil]];
    }


    if(launchOptions != nil){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"alerta"
                                                        message:[launchOptions[UIApplicationLaunchOptionsLocalNotificationKey] description]
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
    }


    NSUUID *beaconUUID = [[NSUUID alloc] initWithUUIDString:@"B39ED98FF-2900-441A-802F-9C398FC199D2"];
    NSString *regionIdentifier = @"iBeacons region 1";
    CLBeaconRegion *beaconRegion = [[CLBeaconRegion alloc] initWithProximityUUID: beaconUUID identifier: regionIdentifier ];
    beaconRegion.notifyEntryStateOnDisplay = YES;
    self.locationManager = [[CLLocationManager alloc]init];



    if([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]){
        [self.locationManager requestAlwaysAuthorization];
    }

    self.locationManager.delegate = self;
    //self.locationManager.pausesLocationUpdatesAutomatically = NO;

    [self.locationManager startMonitoringForRegion:beaconRegion];
    [self.locationManager startRangingBeaconsInRegion:beaconRegion];
    [self.locationManager startUpdatingLocation];


    return YES;
}

-(void)sendLocalNotificationWithMessage:(NSString*)message {
    UILocalNotification *notification = [[UILocalNotification alloc] init];
    notification.alertBody = message;
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
}


- (void) locationManager:(CLLocationManager *)manager didRangeBeacons:(NSArray *)beacons inRegion:(CLBeaconRegion *)region{

    ViewController *viewController = (ViewController*) self.window.rootViewController;
    viewController.beacons = beacons;
    [viewController.tableView reloadData];

    NSString *message = @"";

    if(beacons.count > 0){
        CLBeacon *nearestBeacon = beacons.firstObject;
        if(nearestBeacon.proximity == self.lastProximity || nearestBeacon.proximity == CLProximityUnknown){
            return;
        }
        self.lastProximity = nearestBeacon.proximity;

        switch (nearestBeacon.proximity) {
            case CLProximityFar:
                message = @"CLProximityFar";
                break;
            case CLProximityNear:
                message= @"CLProximityNear";
                break;
            case CLProximityImmediate:
                message= @"CLProximityImmediate";
                break;
            case CLProximityUnknown:
                return;
      }

    }else {
        message = @"No BEACONS";
    }

    NSLog(@"%@", message);
    [self sendLocalNotificationWithMessage:message];

}

- (void) locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region{
    [manager startRangingBeaconsInRegion:(CLBeaconRegion*) region];
    [self.locationManager startUpdatingLocation];

    NSLog(@"INSIDE REGION");
    [self sendLocalNotificationWithMessage:@"INSIDE REGION"];
}

- (void) locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region{
    [manager stopRangingBeaconsInRegion:(CLBeaconRegion*) region];
   [self.locationManager stopUpdatingLocation];

    NSLog(@"OUTSIDE REGION");
    [self sendLocalNotificationWithMessage:@"OUTSIDE REGION"];
}

- (void)locationManager:(CLLocationManager *)manager didDetermineState:(CLRegionState)state forRegion:(CLRegion *)region{

    if (state == CLRegionStateInside) {


        //Start Ranging
        [manager startRangingBeaconsInRegion:(CLBeaconRegion*) region];
        [self.locationManager startUpdatingLocation];

        NSLog(@"INSIDE REGION");
        [self sendLocalNotificationWithMessage:@"INSIDE REGION"];
    }

    else{

        //Stop Ranging
        [manager stopRangingBeaconsInRegion:(CLBeaconRegion*) region];
        [self.locationManager stopUpdatingLocation];

        NSLog(@"OUTSIDE REGION");
        [self sendLocalNotificationWithMessage:@"OUTSIDE REGION"];
    }

}


-(void)application:(UIApplication *)application didReceiveLocalNotification:(NSDictionary *)userInfo {

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"ALERT"
                                                    message:@"didReceiveLocalNotification"
                                                   delegate:nil
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles:nil];
    [alert show];


}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
#导入“AppDelegate.h”
#进口
#导入“ViewController.h”
@接口AppDelegate()
@结束
@实现AppDelegate
-(BOOL)应用程序:(UIApplication*)应用程序使用选项完成启动:(NSDictionary*)启动选项{
if([UIApplication InstanceRespondtoSelector:@selector(registerUserNotificationSettings:)])){
[[UIApplication sharedApplication]registerUserNotificationSettings:[UIUserNotificationSettings设置类型:UIUserNotificationTypeAlert | UIUserNotificationTypeSound
类别:无]];;
}
如果(启动选项!=nil){
UIAlertView*alert=[[UIAlertView alloc]initWithTitle:@“alerta”
消息:[启动选项[UIApplicationLaunchOptions sLocalNotificationKey]说明]
代表:无
取消按钮:@“确定”
其他按钮:无];
[警报显示];
}
NSUID*beaconUUID=[[NSUID alloc]initWithUUIString:@“B39ED98FF-2900-441A-802F-9C398FC199D2”;
NSString*regionIdentifier=@“iBeacons区域1”;
CLBeaconRegion*beaconRegion=[[CLBeaconRegion alloc]initWithProximityUID:beaconUUID标识符:regionIdentifier];
beaconRegion.NotifyEntryStateondDisplay=是;
self.locationManager=[[CLLocationManager alloc]init];
if([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]){
[self.locationManager请求始终授权];
}
self.locationManager.delegate=self;
//self.locationManager.pausesLocationUpdatesAutomatically=否;
[self.locationManager startMonitoringForRegion:beaconRegion];
[self.locationManager startrangingbeaconregion:beaconRegion];
[self.locationManager startUpdatingLocation];
返回YES;
}
-(void)sendLocalNotificationWithMessage:(NSString*)消息{
UILocalNotification*通知=[[UILocalNotification alloc]init];
notification.alertBody=消息;
[[UIApplication sharedApplication]scheduleLocalNotification:notification];
}
-(void)locationManager:(CLLocationManager*)manager DidRange信标:(NSArray*)区域内的信标:(CLBeaconRegion*)区域{
ViewController*ViewController=(ViewController*)self.window.rootViewController;
viewController.beacons=信标;
[viewController.tableView重新加载数据];
NSString*消息=@“”;
如果(beacons.count>0){
CLBeacon*nearestBeacon=beacons.firstObject;
if(nearestBeacon.approxity==self.lastproxity | | nearestBeacon.approxity==CLProximityUnknown){
返回;
}
self.lastproxity=nearestBeacon.approxity;
开关(最接近的信标。接近){
案例CLProximityFar:
消息=@“CLProximityFar”;
打破
病例CLProximityNear:
消息=@“CLProximityNear”;
打破
案例CLProximity立即:
消息=@“CLProximityImmediate”;
打破
案例CLP未知:
返回;
}
}否则{
消息=@“无信标”;
}
NSLog(@“%@”,消息);
[self-sendLocalNotificationWithMessage:message];
}
-(无效)locationManager:(CLLocationManager*)经理区域:(CLRegion*)区域{
[经理StarTrangBeaconRegion:(CLBeaconRegion*)区域];
[self.locationManager startUpdatingLocation];
NSLog(“区域内”);
[self-sendLocalNotificationWithMessage:@“内部区域”];
}
-(无效)locationManager:(CLLocationManager*)经理所在区域:(CLRegion*)区域{
[经理停止管理区域:(CLBEACON区域*)区域];
[self.locationManager停止更新位置];
NSLog(“区域外”);
[self-sendLocalNotificationWithMessage:@“外部区域”];
}
-(void)locationManager:(CLLocationManager*)manager:(CLRegionState)地区的州:(CLRegion*)地区{
如果(状态==CLRegionStateInside){
//开始测距
[经理StarTrangBeaconRegion:(CLBeaconRegion*)区域];
[self.locationManager startUpdatingLocation];
NSLog(“区域内”);
[self-sendLocalNotificationWithMessage:@“内部区域”];
}
否则{
//停止测距
[经理停止管理区域:(CLBEACON区域*)区域];
[self.locationManager停止更新位置];
NSLog(“区域外”);
[self-sendLocalNotificationWithMessage:@“外部区域”];
}
}
-(void)应用程序:(UIApplication*)应用程序收到本地通知:(NSDictionary*)用户信息{
UIAlertView*警报=[[UIAlertView alloc]initWithTitle:@“警报”
消息:@“didReceiveLocalNotification”
代表:无
取消按钮:@“确定”
其他按钮:无];
[警报显示];
}
-(无效)应用程序将重新签名:(UIApplication*)应用程序{
//当应用程序即将从活动状态移动到非活动状态时发送。这可能发生在某些类型的临时中断(如来电或短信)或用户退出应用程序并开始转换到后台状态时。
//使用此方法暂停正在进行的任务、禁用计时器和降低OpenGL ES帧速率。游戏应使用此方法暂停游戏。
}
-(无效)应用程序标识符背景:(UIApplication*)应用程序{
/