Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS re-check location on load from background

I'm building an app which displays result data based on your current location.

At the moment, I'm using the viewDidLoad method of a UIViewController to start the CLLocationManager and getting the current location. Once I have the location that matches the accuracy I desire, I do a request to my web service to get the results and dump it into a UITableView.

My problem is that when you close the app (although it's still running in the background). If you were to drive to another town, re-open the app, the data doesn't get updated and continues to show the results from your old location.

Basically when the UIViewController loads from the background, I need to be able to check the users location, and if they have moved a significant distance, update the contents of my UITableView.

However, because the viewDidAppear of the UIViewController isn't triggered when you load the app from the background, I'm not sure which method I can use.

I am aware of the stopMonitoringSignificantLocationChanges method which wakes up your app when a new location is found. However, this seems a little OTT because I only need to know once the app has loaded.

Is there any alternative to using the stopMonitoringSignificantLocationChanges method?

like image 966
Dan Ellis Avatar asked Dec 07 '22 19:12

Dan Ellis


1 Answers

You could register to receive notifications from UIApplication in -viewDidLoad. You may be interested in UIApplicationDidBecomeActiveNotification. Registering for notifications is easy.

- (void)viewDidLoad
{
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActive:) name:UIApplicationDidBecomeActiveNotification object:nil];
}

In -viewDidLoad we add ourselves as an observer of the UIApplicationDidBecomeActiveNotification and specify a selector to be invoked when that particular notification is received.

- (void)applicationDidBecomeActive:(NSNotification *)notification
{
    // Kick off your CLLocationManager
    [self updateCurrentLocation];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];
}

Finally, remember to remove yourself as an observer for this notification when the view unloads. It's good practice to balance your addObserver/removeObserver calls to NSNotificationCenter in this way.

like image 198
Mark Adams Avatar answered Dec 28 '22 00:12

Mark Adams