Open app with iBeacon

2020-02-29 16:17发布

问题:

I'm so excited about the new release of iOs 7.1 with big changes for iBeacon, which is stated in here: http://beekn.net/2014/03/apple-ios-7-1-launches-major-ibeacon-improvement/

and here: http://beekn.net/2014/03/prisoners-dilemma-ios-7-1-challenges-ibeacon-developers/

According to the topic, they said that

In iOS 7.0 you could just close off the app and it would stop sending you messages. Now, the app doesn’t even need to be open or in the background to work.

As far as I know, you couldn't do anything when an app is closed (not in the background) nor sending any local notification.

So how do you know that if an iOs 7.1 device has enter an iBeacon region? And if you can catch when a closed app enter an iBeacon region, can you wake it up(open it)?

回答1:

In short yes. I've implemented this in an app and upon entering the range of the beacon the call is made to:

- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region;

At that point my app is in the background. If it's been terminated re-opened but stays in the background. The class that I have set to be the CLLocationManager delegate receives the callback to the above method and, in my case, posts a local notification. However you could also trigger opening the app directly.

There's a great little example app on the store called Hide My iPhone by John Yorke. He's opened sourced the code here and it shows how to set up and respond to beacons in an app.

I also used the guide from Apple here to learn more.



回答2:

iOS does launch your app when enters a iBeacon region even if your app was closed completely. You can verify it by doing following things:

  1. Define locationManager in AppDelegate, and add delegate CLLocationManagerDelegate;
  2. Init locationManager in - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    
  3. Add methods:

    - (void)locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region {
        if ([region isKindOfClass:[CLBeaconRegion class]]) {
            UILocalNotification *notification = [[UILocalNotification alloc] init];
            notification.alertBody = @"didExitRegion";
            notification.soundName = @"Default";
            [[UIApplication sharedApplication] presentLocalNotificationNow:notification];
        }
    }
    
    
    - (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region {
        if ([region isKindOfClass:[CLBeaconRegion class]]) {
            UILocalNotification *notification = [[UILocalNotification alloc] init];
            notification.alertBody = @"didEnterRegion";
            notification.soundName = @"Default";
            [[UIApplication sharedApplication] presentLocalNotificationNow:notification];
        }
    }