简体   繁体   English

如何在iphone中暂停和恢复NSTimer

[英]how to pause and resume NSTimer in iphone

hello I am developing small gameApp. 你好我正在开发小型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. NSTimer不会让您暂停它。 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 您可以使用此代码在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; 在.h文件中声明NSDate startDate;

NSTimeInterval pauseTimeinterval; NSTimeInterval pauseTimeinterval; and in viewdidload pausetimeInterval=0.0; 并在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. 但是,当用户转到设置视图时,您可以保存计时器的fireDate以及当前日期。 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). 一旦他/她切换回游戏,您将创建一个新的计时器对象,并将开火日期设置为旧的开火日期加上用户在菜单中的时间(oldTime + currentTime)。

You can't pause an NSTimer. 您无法暂停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. NSTimers无法暂停,模拟暂停它们的方法通常会使它们无效。 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 你可以在这里找到它: 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. 您可以使用我编写的控制器类来创建新的计时器,然后您可以通过调用控制器类上的方法“pauseTimer”和“unpauseTimer”来暂停和取消暂停计时器。

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. 请不要犹豫,在这里回复你的评论,或在Github页面的问题标签上发帖。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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