如何在iPhone中以后台模式获取当前位置?

时间:2012-05-11 14:58:21

标签: ios iphone objective-c cllocationmanager currentlocation

我使用CLLocationManager获取当前位置,我获取当前位置的纬度和经度值。我没有在我的应用中使用Mapview。因此,每当更改当前位置时,我想将当前位置更新到服务器。每隔5分钟我需要调用Web服务并在后台模式和前台模式中将当前位置更新到服务器。

-(void) getCurrentLocation
{
    // To get the current location of the place
    locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self;
    locationManager.distanceFilter = kCLDistanceFilterNone; //whenever we move
    locationManager.desiredAccuracy = kCLLocationAccuracyBest; //100 m
    //Start the location manager, then only updates the current location
    [locationManager startUpdatingLocation];
}

/In Location manager delegate method, if the location is updated it will call and get the values from the newLocation using CLLocation  
-(void) locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    CLLocation *location = [locationManager location];

    // Configure the new event with information from the location
    CLLocationCoordinate2D coordinate = [location coordinate];

    NSString *lat = [NSString stringWithFormat:@"%f", coordinate.latitude];
    NSString *lon = [NSString stringWithFormat:@"%f", coordinate.longitude];
    NSLog(@"dLatitude : %@", lat);
    NSLog(@"dLongitude : %@",lon);

    self.reverseGeocoder = [[[MKReverseGeocoder alloc] initWithCoordinate:newLocation.coordinate] autorelease];
    reverseGeocoder.delegate = self;
    [reverseGeocoder start];


    //Stop the location manager
    [locationManager stopUpdatingLocation];

}

每当位置发生变化时,我想获得特定位置的纬度和经度。

谢谢!

3 个答案:

答案 0 :(得分:0)

如果您需要使用标准位置服务为用户提供连续的位置更新(即使在后台),您可以通过包含UIBackgroundModes键(具有“location”值)将您的应用声明为需要后台位置服务)在你的应用程序的Info.plist文件中。

答案 1 :(得分:0)

将以下代码用于后台和前台任务。

    UIApplication *app = [UIApplication sharedApplication];

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

[NSTimer scheduledTimerWithTimeInterval:300 target:self selector:@selector(updateLocation) userInfo:nil repeats:YES];

-(void)updateLocation{

    // write the code to update location here. this will execute even if in background or foreground
}

答案 2 :(得分:-1)

首先,如果您需要在前台和后台运行程序,请在项目的info.plist中将必需的后台模式添加为位置服务。获取NSString的位置,并尝试使用同步或异步类型将URL发布到服务器的URL。