user3739958
user3739958

Reputation: 37

My NSDate countdown timer changes when I change views

I have a countdown timer from the current date until 10 minutes have passed.

It counts down completely fine when I'm on the view, but when I change views and come back, then the timer stops, could anybody point me in the right direction?

-(void)updateCountdown {

dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"YYYY-MM-dd-HH-mm-ss"];

NSCalendar *calendar = [NSCalendar currentCalendar];
NSUInteger unitFlags = NSMinuteCalendarUnit|NSSecondCalendarUnit;
NSDateComponents *dateComponants = [calendar components:unitFlags fromDate:startingDate toDate:endingDate options:0];

NSInteger minutes = [dateComponants minute];
NSInteger seconds = [dateComponants second];

NSString *countdownText = [NSString stringWithFormat:@"Free Check: %ld:%ld", (long)minutes, (long)seconds];
timeLabel.text = countdownText;

NSLog (@"Startdate is %@", startingDate);
NSLog(@"Enddate is %@", endingDate);

//Attempt at saving the time but I guess this only saves the text?
NSString * saveStringTime = timeLabel.text;
NSUserDefaults * defaultsTime = [NSUserDefaults standardUserDefaults];
[defaultsTime setObject:saveStringTime forKey:@"saveStringTime"];
[defaultsTime synchronize];

[self performSelector:@selector(updateCountdown) withObject:nil afterDelay:1];
}

I think I need something in my ViewDidLoad to get whatever time it was and put that back in?

Thank you

Upvotes: 0

Views: 84

Answers (1)

Santhosh
Santhosh

Reputation: 113

You have to get the "savedStringTime" in viewWillAppear to resume from the "savedTime". Since viewDidLoad will get invoked only if the view is loaded to memory, viewDidLoad will not get invoked when the user navigates back to the same view(since view is still in memory).

To get proper working, Invoke your method to save the time in "viewWillDisappear" and in "viewWillAppear" check if the "savedStringTime" is available, if yes then resume it or else start a fresh counter.

Upvotes: 1

Related Questions