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

时间:2015-01-19 15:45:44

标签: 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 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

我无法找到问题所在,我需要你的帮助!

1 个答案:

答案 0 :(得分:2)

代码看起来不错。在测试时,我建议您执行以下操作:

  1. 启动您的应用
  2. 打开你的灯塔
  3. 验证您是否获得了didEnterRegion回调。
  4. 关掉你的灯塔
  5. 验证您是否获得了didExitRegion回调。
  6. 重新启动手机
  7. 等待至少2分钟(重启后CoreLocation完全启动需要一段时间。)
  8. 打开你的灯塔
  9. 等待几分钟,看看你是否收到了didEnterRegion回调。
相关问题