1

我在我的应用程序中使用核心位置框架。当应用程序第一次启动时,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];
  }
4

2 回答 2

1

在 didUpdateToLocation 内部,当 oldLocation 被接收为 NULL 时,从函数返回。第一次调用您的委托时,它将为 NULL。

其次,您可以获取 currentTime 和 newLocation.timeStamp 之间的时间戳差异。如果它不在可接受的范围内,则从函数返回。

于 2012-06-15T12:30:20.843 回答
0

也许您应该仅在某个时间间隔已过时才调用您的服务器?

int now = (int)[[NSDate date] timeIntervalSince1970];

if(now - self.lastUpdate > INTERVAL_BETWEEN_TWO_UPDATES) {  
    [self callServeur];
    self.lastUpdate = now;
}
于 2012-06-15T12:08:44.193 回答