[英]How to get current location in background mode and keep sending that location to server in background mode
[英]How do i get the current location in the background mode in iPhone?
我正在使用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];
}
每當位置更改時,我想獲取特定位置的緯度和經度。
謝謝!
如果您需要使用標准位置服務向用戶提供連續的位置更新(即使在后台),則可以通過在您的應用程序中包含UIBackgroundModes鍵(帶有“ location”值)來聲明您的應用需要背景位置服務應用程序的Info.plist文件。
將以下代碼用於背景和前景任務。
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
}
首先,如果您需要程序在前台和后台運行,請在項目的info.plist中將“必需的后台”模式添加為定位服務。 將位置獲取為NSString,然后嘗試使用同步類型或異步類型將URL發布到服務器的URL中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.