When should I stop updating location manager?

坚强是说给别人听的谎言 提交于 2019-12-10 21:08:55

问题


I have an app that makes a call to get the user's location:

-(void)getLocation{
    locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self;
    locationManager.distanceFilter = kCLDistanceFilterNone;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    [locationManager startUpdatingLocation];

}
//SET USER LOCATION
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    self.userLocation = [locations lastObject];
    NSLog(@"location in IntroVC %f, %f", self.userLocation.coordinate.latitude, self.userLocation.coordinate.longitude);
}

My question is, because that NSLog keeps spitting out a new location infinitely, when should I stop calling the location? Well I guess its really up to my app's functionality, but doesnt this cause battery drain? If so, I should really look into the best way of stopping the updates.


回答1:


Your Distance filter of the location manager is set to be kCLDistanceFilterNone. This causes the didUpdateLocations method to be called infinite time.

locationManager.distanceFilter = kCLDistanceFilterNone;

Change this line as

locationManager.distanceFilter = 10;

and try again. Change the value as needed.

So now the didUpdateLocation will not be called infinite times. :)

Hopefully this helps.




回答2:


Depending on the nature of your app, you may well want to turn location services off when you go into the background or when the screen is locked. These notifications hooks are provided generally in your app delegate file (.m). Yes you are right, location services significantly drain battery and it a highly recommended practice for iOS apps using location services to use it cautiously.

Apple seems to have thought about this and has provided an API that notifies the app only if the user has moved "significantly" Apple the significant change location service. The definition of "moved significantly" varies on various aspects depending on WiFi availability, cell tower availability, GPS availability etc. Luckily all this is obfuscated within this API.




回答3:


I call this method after updating the location in didupdateloactions, so when my app goes in background it remove location icon from top status bar.



来源:https://stackoverflow.com/questions/16930850/when-should-i-stop-updating-location-manager

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!