Search code examples
ioscllocationmanageribeacon

iOS Location Background Mode Running Time


We are doing some work with beacons and iOS and investigating the options for applying a debounce between when we first go in range of the beacon and when we raise a notification to the user.

So the flow would be,

  1. Go in range of a beacon.
  2. Start a timer.
  3. Timer expires, post notification.

Their doesn't seem to be any complications doing this when the app is in the foreground but I'm not sure how this will work with the app closed.

If we register the location background mode then the app will get started when we go in range of a beacon but its unclear to me how long the app we'll be allowed to run. If the app is only allowed to run for a very short period of time then we won't have time to start a timer and have it expire.

Can anyone shed any light on how much execution time the location background mode allows an app when started in the background like this?


Solution

  • I would suggest that once you enter the beacon region that you start ranging the beacon - this will provide you with ranging callbacks at the rate of one per second - even if your app is in the background. You can count these events and use that to determine when you will post the notification. At this point you can stop ranging the beacon.

    - (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region {
        [manager startRangingBeaconsInRegion:(CLBeaconRegion *)region];
        self.beaconCount=0;
    }
    
    -(void)locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region {
        [manager stopRangingBeaconsInRegion:(CLBeaconRegion*)region];
    }
    
    - (void)locationManager:(CLLocationManager *)manager
            didRangeBeacons:(NSArray *)beacons
                   inRegion:(CLBeaconRegion *)region {
            self.beaconCount++;
            if (self.beaconCount > SOME_THRESHOLD) {
                [manager stopRangingBeaconsInRegion:region];
                [self postLocalNotification];
            }
    }
    

    Because this is using the location background mode there is no overall limit to the amount of background time available, but there is a limit on each invocation of a delegate method of a few seconds - but this code won't be anywhere near that.