首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在ios8中保持在后台连续获取位置?

如何在ios8中保持在后台连续获取位置?
EN

Stack Overflow用户
提问于 2015-05-13 15:01:39
回答 2查看 925关注 0票数 0

如何在iOS8中保持后台连续定位,同时又要尽量省电?有人能给我一些建议吗?

EN

回答 2

Stack Overflow用户

发布于 2015-05-13 15:18:11

在您的项目设置中,选择Target并转到Capabilities,打开后台模式,勾选location updatesbackground fetch。这将在你的项目plist中添加背景模式。

现在,为了即使在后台也能获得连续的位置更新,可以在AppDelegate的applicationDidEnterBackground:方法中添加以下代码。这段代码每次都会杀死后台任务,然后重新启动它。因此,即使应用程序在后台,您也会收到后台位置更新

代码语言:javascript
复制
- (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:方法,因为它仅在位置根据所需精度更改时才会调用。

代码语言:javascript
复制
- (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
EN

Stack Overflow用户

发布于 2015-05-13 15:16:08

Found some Solution here

研究Ray Wenderlich中的示例。示例代码运行得很好。

你可以通过使用这个代码片段来添加计时器,这可能会减少一点电池消耗:

代码语言:javascript
复制
-(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];
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30207806

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档