如何在iOS8中保持后台连续定位,同时又要尽量省电?有人能给我一些建议吗?
发布于 2015-05-13 15:18:11
在您的项目设置中,选择Target并转到Capabilities,打开后台模式,勾选location updates和background fetch。这将在你的项目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];
}
}发布于 2015-05-13 15:16:08
研究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];
}https://stackoverflow.com/questions/30207806
复制相似问题