Getting user location when app is in background. IOS

别说谁变了你拦得住时间么 提交于 2019-12-07 01:55:34

This is what works for me, I use CLLocationManagerDelegate, register for updates on didUpdateLocations and in app Delegate

- (void)applicationDidBecomeActive:(UIApplication *)application {
    [_locationManager stopMonitoringSignificantLocationChanges];
    [_locationManager startUpdatingLocation];
}

I start updating location, the key for me, is when the app goes to background I switch to Significant Location Changes so the app doesn't drain the batter like this:

- (void)applicationDidEnterBackground:(UIApplication *)application {
    [_locationManager startMonitoringSignificantLocationChanges];
}

In didUpdateLocations, you can check

BOOL isInBackground = NO;
if ([UIApplication sharedApplication].applicationState == UIApplicationStateBackground)
{
    isInBackground = YES;
}

And start a task in the background to report the location for example

if (isInBackground) {
    [self sendBackgroundLocationToServer:self.location];
}

And start a task, I hope that helps.

Getting user's location in background on SignificantLocationChanges with high accuracy(using gps)

Do the following:

in info.plist add the following

    <key>NSLocationAlwaysUsageDescription</key>
    <string>{your app name} requests your location coordinates.</string>
    <key>UIBackgroundModes</key>
    <array>
        <string>location</string>
    </array>

in code use LoctionManager to get location updates, (it will work in both foreground and background)

@interface MyViewController <CLLocationManagerDelegate>
@property (nonatomic, strong) CLLocationManager *locationManager;
@end 

@implementation MyViewController
-(void)startLocationUpdates {
    // Create the location manager if this object does not
    // already have one.
    if (self.locationManager == nil) {
        self.locationManager = [[CLLocationManager alloc] init];
    }

    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
    self.locationManager.activityType = CLActivityTypeFitness;

    // Movement threshold for new events.
    self.locationManager.distanceFilter = 25; // meters

    if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
        [self.locationManager requestAlwaysAuthorization];
    }
    [self.locationManager startUpdatingLocation];
}

- (void)stopLocationUpdates {
    [self.locationManager stopUpdatingLocation];
}

#pragma mark CLLocationManagerDelegate

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    // Add your logic here
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    NSLog(@"%@", error);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!