Proper way of using CLLocationManager (to start/stop updating user location)

Deadly 提交于 2020-01-03 04:14:18

问题


I have a UIView with an MKMapView, in a UIViewController, which appears only when user taps a button.

The process is as follows:

  • A CLLocationManager object is declared as private member in the header file.
  • A UIView with an MKMapView is presented (initially the frame is outside bounds. Is moved to within view bounds on user's action, WITHIN THE SAME viewController).
  • It is initialized:

    locationManager = [[CLLocationManager alloc]  init];
    locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
    locationManager.desiredAccuracy = kCLLocationAccuracyBest; // 100 m
    [locationManager startUpdatingLocation];
    CLLocation *location = [locationManager location];
    CLLocationCoordinate2D coordinate = [location coordinate];
    
    MKCoordinateSpan span = MKCoordinateSpanMake(0.04, 0.04);
    MKCoordinateRegion region = MKCoordinateRegionMake(coordinate, span);
    mapView.showsUserLocation = YES;
    [mapView setRegion:region animated:YES];
    
  • Nearby locations are fetched using Foursquare API

Now, I wish to stop the location lock, when the view is removed from visible bounds. I tried it with stopUdatingUserLocation. I also released the locationManager, but the GPS lock icon is persistent in the statusBar. As I understand, continuous GPS lock drains the battery, and I would like to stop that. How would I go about it ?


回答1:


Even tho it's not officially documented, it would be better to use only one CLLocationManager throughout your whole app. Treat it as a singleton, don't initialise it every time, and it should work properly.



来源:https://stackoverflow.com/questions/18918019/proper-way-of-using-cllocationmanager-to-start-stop-updating-user-location

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