简体   繁体   中英

how to pause and resume NSTimer in iphone

hello I am developing small gameApp. I need to pause the timer,when user goes to another view [say settings view]. when user comes back to that view , I need to resume the timer.

can anybody solve this issue ...

Thanks in Advance...

NSTimer does not give you the ability to pause it. However, with a few simple variables, you can create the effect yourself:

NSTimer *timer;
double timerInterval = 10.0;
double timerElapsed = 0.0;
NSDate *timerStarted;

-(void) startTimer {
  timer = [NSTimer scheduledTimerWithTimeInterval:(timerInterval - timerElapsed) target:self selector:@selector(fired) userInfo:nil repeats:NO];
  timerStarted = [NSDate date];
}

-(void) fired {
  [timer invalidate];
  timer = nil;
  timerElapsed = 0.0;
  [self startTimer];
  // react to timer event here
}

-(void) pauseTimer {
  [timer invalidate];
  timer = nil;
  timerElapsed = [[NSDate date] timeIntervalSinceDate:timerStarted];
}

This has been working out quite well for me.

you can use this code to implement pause and resume functionality in NSTimer

//=========new timer update method=============

-(void) updateTimer {

    NSDate *currentDate = [NSDate date];

    NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate];
    NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];


    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"mm:ss.S"];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];

    NSString *timeString = [dateFormatter stringFromDate:timerDate];
    lblMessage.text = timeString;
    pauseTimeInterval = timeInterval;

   }

 -(IBAction) startBtnPressed:(id)sender
    {
//=============================new update with start pause==================
if(running == NO) {
    running = YES;

    startDate = [NSDate date] ;
    startDate = [[startDate dateByAddingTimeInterval:((-1)*(pauseTimeInterval))] retain];
    stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/10.0 target:self selector:@selector(updateTimer) userInfo:nil repeats:YES];
}
else {
    running = NO;
    [stopWatchTimer invalidate];
    stopWatchTimer = nil;
    [self updateTimer];
}
}

declare in .h file NSDate startDate;

NSTimeInterval pauseTimeinterval; and in viewdidload pausetimeInterval=0.0; good luck

You can't pause a timer. However, when the user goes to the settings view, you can save the fireDate of the timer and also the current date. After this you invalidate the timer and let the user do his/her stuff. Once he/she switches back to the game, you create a new timer object and set the fire date to the old fire date plus the time the user was in the menu (oldTime + currentTime).

You can't pause an NSTimer. You can, however invalidate it and create a new one when needed.

on Start - 
startNewCapture = [NSDate date];

on Pause - 
captureSessionPauseDate = [NSDate date]; 
captureSessionTimeInterval = [captureSessionPauseDate timeIntervalSinceDate:startNewCapture];

on Resume - 
NSDate *dateNow = [NSDate date];
startNewCapture = [NSDate dateWithTimeInterval:-captureSessionTimeInterval sinceDate:dateNow];
- (IBAction)pauseResumeTimer:(id)sender {

    if (timerRunning == NO) {
        timerRunning = YES;

    [pauseTimerBtn setTitle:@"Resume" forState:UIControlStateNormal];
    NSString *stringVal = [NSString stringWithFormat:@"%@",timeTxt.text];
    stringVal = [stringVal stringByReplacingOccurrencesOfString:@":" withString:@"."];

    float tempFloatVal = [stringVal floatValue];
    int minuteValue = floorf(tempFloatVal);
    float tempSecVal = [stringVal floatValue] - floorf(tempFloatVal);
    int secondVal = tempSecVal*100;
    minuteValue = minuteValue*60;

    oldTimeValue = minuteValue + secondVal;
    [timer invalidate];
    timer = nil;
}
else
{
    timerRunning = NO;
    [pauseTimerBtn setTitle:@"Pause" forState:UIControlStateNormal];
    startDate = [NSDate date];
    timer = [NSTimer scheduledTimerWithTimeInterval:0.25 target:self selector:@selector(timer:) userInfo:nil repeats:YES];
    }    
}

- (void)runTimer:(NSTimer *)timer {
    NSInteger secondsAtStart = (NSInteger)[[NSDate date] timeIntervalSinceDate:startDate];
    secondsAtStart = secondsAtStart + oldTimeValue;
    NSInteger seconds = secondsAtStart % 60;
    NSInteger minutes = (secondsAtStart / 60) % 60;
    NSInteger hours = secondsAtStart / (60 * 60);
    NSString *result = nil;
    result = [NSString stringWithFormat:@"%02ld:%02ld",(long)minutes,(long)seconds];
    timeTxt.text   =  result;

}

Did you end up figuring it out? I saw that you said that you cannot invalidate your timer when you go into another view. Can you explain what you mean by that? NSTimers cannot be paused, and methods to simulate pausing them usually involve invalidating them. You can then simulate "unpausing" by creating a new timer that will then start up again. This will simulate a timer being paused and unpaused.

For people who would like a potentially more convenient method, I wrote a controller class that can conveniently handle pausing and unpausing timers. You can find it here: https://github.com/LianaChu/LCPausableTimer

You can use the controller class that I wrote to create new timers, and then you can pause and unpause the timers by call the methods "pauseTimer" and "unpauseTimer" on the controller class.

I would greatly appreciate any comments or feedback like how you used it, what changes you would like to see, or any features you would like me to add. Please don't hesitate to reply with your comments here, or post on the issues tab on the Github page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM