4
votes

I've done a lot of searching around SO and Google to try to get an answer for this but I haven't been able to put all the pieces of the jigsaw together so any help/pointers would be great.

I'd like to build an app that checks a web service when it enters an iBeacon region. Simple example use case would be this:

  1. user walks into an iBeacon equipped store with app in background

  2. rather than notify the user, the app makes a request to a web server to check if the user ID is a member (the app has been granted permission to send a user ID to the server by the user).

3a. server sends back "true" response

4a. app sends "We have a special members promotion today" notification to lock screen.

OR

3b. server sends back "false" response

4b. app stays silent (no notification to user)

FYI this answer seems to suggest it's possible to send a URL request in the background: Running URL Requests in the Background

2

2 Answers

5
votes

You've pretty much identified everything you need to do.

When your CLLocationManagerDelegate's didEnterRegion: method is called, you can start a background task, and then kick off a network request. Once you've received a response, you can deliver a local notification if necessary, and then end the background task.

- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region
{
    // If not already performing a background task for this region...

    UIBackgroundTaskIdentifier bgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTask];
        self.backgroundTask = UIBackgroundTaskInvalid;
    }];

    // perform network request - if successful, display notification. when finished, end background task
}

Although I should note I wouldn't actually place background task management and web request code directly inside my didEnterRegion: method. I'd have a separate web API class which performs the requests, and just make calls to that from within didEnterRegion:.