Clay Freeman
Clay Freeman

Reputation: 543

How to Monitor Location in Background in iOS?

I am currently writing a home automation app for a client which will open their garage, turn on the living room and office lights, and other such things when they arrive within 150 meters of their home. It will do the opposite when they leave. I am very grateful that geofencing is built into iOS, and the feature works perfectly when the app is in the foreground, but when the user closes the app, and the phone is still monitoring a geofence, the app does nothing when an event occurs. Is there a separate method other than locationManager:didEnterRegion: that I should be implementing for background notifications to my app? Here is the code that I am using right now:

- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region {
    NSLog(@"Entered Region - %@", region.identifier);
    [self showRegionAlert:@"Entering Region" forRegion:region.identifier];
    [self sendCommand:true];
}

- (void)locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region {
    NSLog(@"Exited Region - %@", region.identifier);
    [self showRegionAlert:@"Exiting Region" forRegion:region.identifier];
    [self sendCommand:false];
}

Upvotes: 1

Views: 840

Answers (3)

Shibin S
Shibin S

Reputation: 149

Turn on BackgroundModes in Target Settings/Capabilities and enable Location Updates. Since app is in background, you will get little time for processing and the app will move to sleep mode. Use expirationHandler make app active for some more time for doing large processing.

Upvotes: 0

Clay Freeman
Clay Freeman

Reputation: 543

I discovered it was a non-issue. It all works exactly the same way as if the app were active. The same method is called. I made sure to optimize the app for background launch though so that it would be more of an instant response. I guess I was doing something wrong though, or it just wasn't working at first.

Upvotes: 1

brightintro
brightintro

Reputation: 1016

To use location services while your app is in the background you need to change your app's info plist file. Should be found in Supporting Files folder and look like this, YourAppName-Info.plist

Add an item to the Information Property List and type in Required Background Modes as the key, which is of type Array. Add an item to that array and type in App registers for location updates into the value of that item.

Upvotes: 1

Related Questions