0

I've got an iPhone app that I've made, that on one view has a UIDatePicker.

When you initially launch the app - and the view first loads; inside the viewDidLoad I have the UIDatePicker get set to the current date/time. It works fine.

Now if the user minimizes the app and does other things (but does not kill the app) and then goes back to the app, the date/time does not update when you go back to that view.

I'm wondering how I would go about making it 'refresh' that UIDatePicker any time the view is loaded (for example, when you go back to it after it's already been opened but is sitting in the background).

Any thoughts?

If there's no quick/easy way - I also considered creating a time related variable when the UIDatePicker loads initially - then when it is reloaded having it check to see if more than 10 minutes had passed since the last view. If so, then it would set the UIDatePicker to current date/time.

Any ideas?

Hanny
  • 2,078
  • 6
  • 24
  • 52

2 Answers2

3

Your view did load could look something like this

- (void)viewDidLoad {
    [super viewDidLoad];

    // listen for notifications for when the app becomes active and refresh the date picker
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshDatePicker) name:UIApplicationDidBecomeActiveNotification object:nil];
}

Then in your viewWillAppear:

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    // refresh the date picker when the view is about to appear, either for the
    // first time or if we are switching to this view from another
    [self refreshDatePicker];
}

And implement the refresh method simply as:

- (void)refreshDatePicker {
    // set the current date on the picker
    [self.datepicker setDate:[NSDate date]];
}

This will update your date picker in both cases, when the view is switched from another view to this view while the application is open, and when the app is backgrounded and comes to the foreground with that view already open.

Mike
  • 9,765
  • 5
  • 34
  • 59
  • This worked great - thanks! I was in a bit of a bind - for fear that if people are entering data from previous dates (this is a trip logging app) they might leave the screen to edit something and come back and have to reset the date - but that slight inconvenience is well worth having people potentially entering wrong dates entirely because they forgot to close the app and/or check the date picker before entering their info. Thanks again! – Hanny Sep 05 '14 at 14:43
0

You should be able to set the date in the viewWillAppear method. That method is called each time the view will appear on screen.

- (void) viewWillAppear: (BOOL) animated 
{
    [super viewWillAppear:animated];
    // update the date in the datepicker
    [self.datepicker setDate:[NSDate date]];
}
Rool Paap
  • 1,918
  • 4
  • 32
  • 39