且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

当应用程序在后台时获取用户位置。 iOS

更新时间:2022-12-26 11:25:39

这对我有用,我使用 CLLocationManagerDelegate ,在上注册更新didUpdateLocations 和应用程序委托

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];
}

在didUpdateLocations中,您可以检查

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.