2012-05-11 20 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 
} 
相關問題