ios,每小时获取一次位置(ios7)

时间:2014-02-24 15:16:32

标签: ios cllocationmanager

在我的项目中,我需要获取位置。我的代码如下所示:

#import "AppDelegate.h"

@implementation AppDelegate {
   UIBackgroundTaskIdentifier bgTask;
   CLLocationManager *locationManager;
}


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

   locationManager = [[CLLocationManager alloc] init];
   locationManager.delegate = self;
   locationManager.pausesLocationUpdatesAutomatically = NO;
   locationManager.activityType = CLActivityTypeOther;
   locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
   locationManager.distanceFilter = kCLDistanceFilterNone;

   return YES;
}                       

- (void)applicationDidEnterBackground:(UIApplication *)application {
   __block UIBackgroundTaskIdentifier background_task;

   background_task = [application beginBackgroundTaskWithExpirationHandler:^ {
    [application endBackgroundTask: background_task];
    background_task = UIBackgroundTaskInvalid;
   }];

   dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

    [locationManager startUpdatingLocation];

    while(TRUE)
    {
        NSLog(@"Background time Remaining: %f",[[UIApplication sharedApplication] backgroundTimeRemaining]);
        [NSThread sleepForTimeInterval:200]; //wait for x sec

        [locationManager startUpdatingLocation];
    }

    [application endBackgroundTask: background_task];
    background_task = UIBackgroundTaskInvalid;
   });


}

- (void) locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {

   CLLocation *location = [locations lastObject];

   NSDate* eventDate   = location.timestamp;
   NSTimeInterval time = [eventDate timeIntervalSinceNow];
   if (abs(time) < 15.0) {
    if (location != nil) {

        NSString *lat = [NSString stringWithFormat:@"%.8f", location.coordinate.latitude];
        NSString *lng = [NSString stringWithFormat:@"%.8f", location.coordinate.longitude];

        NSLog(@"location update  ...");

        //[APIConnection SaveMyPositionWitLat:lat withLng:lng];
        //[locationManager stopUpdatingLocation];
    }
   }
}

这样可行,但我的手机电池耗电非常快,位置每秒检查一次。如果我启用:

[locationManager stopUpdatingLocation];

然后定位服务永久停止。如何更改此代码以节省电池电量?

2 个答案:

答案 0 :(得分:1)

由于您的应用需要有效的位置监控才能继续在后台运行,因此您无法在iOS中获取该位置。

为此,Apple有方法只检查主要更改,startMonitoringSignificantLocationChanges

这将通知您应用程序位置的任何重大更改。那么你可以做些什么来获得更准确的位置就是开始正常的startUpdatingLocation

这样可以节省电量,只在需要时抓取位置。

答案 1 :(得分:0)

您可以将locationManager.pausesLocationUpdatesAutomatically设置为YES这应该有用吗