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?
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.
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]];
}