2012-05-11 28 views
2

我使用CLLocationManager获取当前位置,并获取当前位置的纬度和经度值。我没有在我的应用中使用Mapview。所以无论何时当前位置发生变化,那个时候我都想将当前位置更新到服务器。并且每隔5分钟我需要调用Web服务并将当前位置更新到背景模式和前景模式中的服务器。我如何在iPhone中获取背景模式中的当前位置?

-(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]; 

} 

每当位置发生变化,那个时候我想为特定位置的经度和纬度。

谢谢!

回答

-1

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

0

如果您需要使用标准位置服务向用户提供持续位置更新(即使在后台),您可以声明您的应用程序需要后台位置服务,方法是将UIBackgroundModes项(包括“位置”价值)在您的应用程序的Info.plist文件中。

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 
} 
相关问题