How to stop multiple times method calling of didUpdateLocations() in ios

前端 未结 10 1154
無奈伤痛
無奈伤痛 2020-11-28 06:45

This my code......

 -(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
 {

    location_updated = [locations lastObj         


        
10条回答
  •  被撕碎了的回忆
    2020-11-28 07:22

    for the time constraint, i did not understand code from accepted answer, posting a different approach. as Rob points out "When you first start location services, you may see it called multiple times". the code below acts on the first location, and ignores the updated locations for first 120 seconds. it is one way to address orginal question "How to stop multiple times method calling of didUpdateLocations".

    in .h file:

    @property(strong,nonatomic) CLLocation* firstLocation;
    

    in .m file:

    // is this the first location?
        CLLocation* newLocation = locations.lastObject;
        if (self.firstLocation) {
            // app already has a location
            NSTimeInterval locationAge = [newLocation.timestamp timeIntervalSinceDate:self.firstLocation.timestamp];
            NSLog(@"locationAge: %f",locationAge);
            if (locationAge < 120.0) {  // 120 is in seconds or milliseconds?
                return;
            }
        } else {
            self.firstLocation = newLocation;
        }
    
        // do something with location
    

提交回复
热议问题