我的最终目标是,每当地点发生变化时,我都需要向网络服务器发送lat和logitude。
我使用下面的代码在每2分钟后将设备的纬度和经度发送到网络服务器,但是当位置发生变化时,它有时没有给出正确的纬度和经度。
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation
*)newLocation fromLocation:(CLLocation *)oldLocation
{
NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow];
NSLog(@"Location Age%@",[NSString stringWithFormat:@"%d",locationAge]);
if (locationAge > 5) return;
// test that the horizontal accuracy does not indicate an invalid measurement
if (newLocation.horizontalAccuracy < 0) return;
NSString *stringUrl;
// BOOL check = FALSE;
NSLog(@"Before condition condition");
if(bestEffortAtLocation == nil || bestEffortAtLocation.horizontalAccuracy > newLocation.horizontalAccuracy){
NSLog(@"condition");
self.bestEffortAtLocation = newLocation;
if (newLocation.horizontalAccuracy <= locmanager.desiredAccuracy) {
// we have a measurement that meets our requirements, so we can stop updating the location
// IMPORTANT!!! Minimize power usage by stopping the location manager as soon as possible.
[locmanager stopUpdatingLocation];
locmanager.delegate = nil;
}
//check = TRUE;
}
stringUrl = [NSString stringWithFormat:URLSAVELAT,stringUserId,[NSString stringWithFormat:@"%g",self.bestEffortAtLocation.coordinate.latitude],[NSString stringWithFormat:@"%g",self.bestEffortAtLocation.coordinate.longitude]];}
对于位置管理员,我使用下面的代码
{
locmanager = [[CLLocationManager alloc] init];
[locmanager setDelegate:self];
locmanager.distanceFilter = 10.0;
//locmanager.distanceFilter = kCLDistanceFilterNone;
[locmanager setDesiredAccuracy:kCLLocationAccuracyBest];
[locmanager startUpdatingLocation];
}
任何,即使很小的帮助也会受到赞赏,谢谢你提前
答案 0 :(得分:3)
您应该使用API中的位置更新回调并使用updateLocation方法:
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
if([self.delegate conformsToProtocol:@protocol(CoreLocationControllerDelegate)]) {
[self.delegate locationUpdate:newLocation];
}
}
然后在viewcontroller中执行此操作:
- (void)locationUpdate:(CLLocation *)location {
//DO WHATEVER YOU WANT HERE, INCLUDING SENDING TO SERVER
}
您还需要定义两个协议方法,其中一个是locationUpdate:
@protocol CoreLocationControllerDelegate
@required
- (void)locationUpdate:(CLLocation *)location;
- (void)locationError:(NSError *)error;
@end
我不建议您在didUpdateLocation:方法中执行所有操作。