mrd
mrd

Reputation: 4699

iOS: LocationManager updates, when to stop updating?

I have a view controller, which queries the LocationManager for the location by receiving updates. I only need the location once, for a Google Places search. There is a segmented control, which lets the user choose, if he wants to use his current location or enter an address. Now, I am concerned with stopping updates. Let's say the user opens the view controller. Initially the segmented control is set to "enter address". Once the user taps it to switch to "current location", I start receiving location updates. This works fine. If the user dismisses the view controller, I stop the updates. But what would happen, if the user presses the home button and performs some other tasks? The view controller goes into background and would still receive updates, which I don't want. I want tha in this case, updates are stop and once the user brings the view controller into the foreground again, the updates should be started again.

In which life cycle method do I put [self.locationManager stopUpdatingLocation]; and [self.locationManager startUpdatingLocation];?

Upvotes: 0

Views: 83

Answers (1)

Himanshu Joshi
Himanshu Joshi

Reputation: 3399

Add the delegate CLLocationManagerDelegate to your delegate file.

then in AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    //create new CLLocationManager
    locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self;

    return YES;
}


- (void)applicationDidEnterBackground:(UIApplication *)application
{
    [locationManager stopUpdatingLocation];
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    [locationManager startUpdatingLocation];
}

and then in your View file you can handle it as required by you.

Upvotes: 1

Related Questions