如何在ios8中继续在后台继续获取位置?

时间:2015-05-13 07:01:39

标签: ios objective-c cllocationmanager battery cllocation

如何在iOS8中继续在后台持续获取位置,您必须尽力节省电力?有人可以给我一些建议吗?

2 个答案:

答案 0 :(得分:1)

在项目设置中,选择目标并转到功能,打开背景模式并勾选位置更新后台提取。 这将在项目plist中添加背景模式。

现在,要在后台获得连续的位置更新,请在AppDelegate的 applicationDidEnterBackground:方法中添加此代码。此代码将每次终止后台任务并重新启动它。因此,即使应用处于后台,您也会收到背景位置更新

- (void)applicationDidEnterBackground:(UIApplication *)application {
    if ([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)]) { //Check if our iOS version supports multitasking I.E iOS 4
        if ([[UIDevice currentDevice] isMultitaskingSupported]) { //Check if device supports mulitasking
            UIApplication *application = [UIApplication sharedApplication]; //Get the shared application instance

            __block UIBackgroundTaskIdentifier background_task; //Create a task object

            background_task = [application beginBackgroundTaskWithExpirationHandler: ^{
                [application endBackgroundTask:background_task]; //Tell the system that we are done with the tasks
                background_task = UIBackgroundTaskInvalid; //Set the task to be invalid
                //System will be shutting down the app at any point in time now
            }];
        }
    }
}

现在为了延长设备电池寿命,您可以使用locationManager:didUpdateLocations:方法,因为只有在位置根据所需精度更改时才会调用它。

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation *location = [locations lastObject];
    if (location != nil) {
        strLatitude  = [NSString stringWithFormat:@"%f", location.coordinate.latitude];
        strLongitude = [NSString stringWithFormat:@"%f", location.coordinate.longitude];
    }
}

答案 1 :(得分:0)

Found some Solution here

研究Ray Wenderlich中的示例。示例代码完美无缺。

您可以使用此代码段向其添加计时器,这可能会减少电池消耗:

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

  UIApplication* app = [UIApplication sharedApplication];

  bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
    [app endBackgroundTask:bgTask];
    bgTask = UIBackgroundTaskInvalid;
  }];

  self.timer = [NSTimer scheduledTimerWithTimeInterval:intervalBackgroundUpdate
                                                target:self.locationManager
                                              selector:@selector(startUpdatingLocation)
                                              userInfo:nil
                                               repeats:YES];
}