I need to start NSTimer by 0:0:0 that I am doing and I have a Pause button on click of that the timer has to pause after some time if a user clicks play it has to run from paused value of time. How can I pause and play in NSTimer? Any help? Thanks in advance.
When you want to stop or “pause” a Timer , you must destroy ( invalidate() ) it as I showed you above and will show you in the next code snippet. If you read the documentation on Timer , you should've noted that: Once scheduled on a run loop, the timer fires at the specified interval until it is invalidated.
Try this shizzle... worked great for me
EDIT
To be honest my actual code is this:
-(IBAction)clicked:(id)sender
{
if ([startStop.titleLabel.text isEqualToString:@"Start"])
{
[startStop setTitle:@"Pause" forState:UIControlStateNormal];
[startStop setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countUp) userInfo:nil repeats:YES];
timerDown = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countDown) userInfo:nil repeats:YES];
} else if ([startStop.titleLabel.text isEqualToString:@"Pause"])
{
[startStop setTitle:@"Resume" forState:UIControlStateNormal];
[startStop setTitleColor:[UIColor colorWithRed:0/255 green:0/255 blue:255/255 alpha:1.0] forState:UIControlStateNormal];
pauseStart = [[NSDate dateWithTimeIntervalSinceNow:0] retain];
previousFireDate = [[timer fireDate] retain];
[timer setFireDate:[NSDate distantFuture]];
} else if ([startStop.titleLabel.text isEqualToString:@"Resume"])
{
[startStop setTitle:@"Pause" forState:UIControlStateNormal];
[startStop setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
float pauseTime = -1*[pauseStart timeIntervalSinceNow];
[timer setFireDate:[NSDate dateWithTimeInterval:pauseTime sinceDate:previousFireDate]];
[pauseStart release];
[previousFireDate release];
}
}
I used a UIButton and used this code when clicked.
remember to put this:
NSDate *pauseStart, *previousFireDate;
in your .h file
EDIT!
here is the countUp method. forget the down method. seconds, minutes, hours are Ints
- (void)countUp
{
seconds += 1;
if (seconds == 60)
{
seconds = 0;
minutes++;
if (minutes == 60)
{
minutes = 0;
hours++;
}
}
}
You don’t. Instead of pausing simply invalidate and release the old timer and when the users presses Play again, create a fresh timer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With