我在我的应用程序中使用核心位置框架。当应用程序第一次启动时,didUpdateToLocation方法被调用两次。我分配了位置管理器实例并启动它并调用startUpdatingLocation。在didUpdateToLocation中,我正在调用另一个函数,我将当前的纬度和经度发送到服务器,那么如何避免多次调用此函数?
- (void)viewDidLoad
{
[super viewDidLoad];
self.locationManager = [[CLLocationManager alloc] init];
[self.mapView setShowsUserLocation:YES];
if( [CLLocationManager locationServicesEnabled])
{
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.delegate = self;
[locationManager startUpdatingLocation];
locationManager.distanceFilter = 1000.0f;
else
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"GPS Disabled" message:@"Enable GPS settings to allow the application to search for your current location" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alertView show];
[alertView release];
}
}
//Here is didUpdateToLocation method
-(void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
self.lat = newLocation.coordinate.latitude;
self.longi = newLocation.coordinate.longitude;
NSLog(@"Updated Location : lat--%f long--%f",self.lat,self.longi);
[self updateUserLocation];
}
//in this function i am sending the latitude and longitude to server.
-(void)updateUserLocation
{
NSString *urlString = [[NSString stringWithFormat:@"http://appifylabs.com/tracemybuddies/index.php/iphone/updateUserLocation/?userId=1&latitude=%@&longitude=%@",self.lat,self.longi] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[conn url_Connection:urlString withActivityView:self.activityView withParentView:self.view];
}
答案 0 :(得分:1)
在didUpdateToLocation内部,当oldLocation被收到为NULL时,从函数返回。 第一次调用您的委托时,它将为NULL。
其次,您可以获取currentTime和newLocation.timeStamp之间的时间戳差异。如果它没有达到可接受的限制,则从函数返回。
答案 1 :(得分:0)
也许你应该只在某个时间间隔过去后调用你的服务器?
int now = (int)[[NSDate date] timeIntervalSince1970];
if(now - self.lastUpdate > INTERVAL_BETWEEN_TWO_UPDATES) {
[self callServeur];
self.lastUpdate = now;
}