繁体   English   中英

如何在iPhone的背景模式下获取当前位置?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM