Tejas Patel
Tejas Patel

Reputation: 870

iOS How to start and pause timer

I develop One Application. In my application, there are Two UIButtons , StartBtn and StopBtn, And also I use NSTimer.

Now, i want to start NSTimer when user click on StartBtn and also stop when your click on StopBtn.

I want to set NSTimer for 1 minute and if i stop timer in 30 sec. then remaining 30 sec. will again start when i click on StartBtn again and after complete 1 minute it should display alertMessage.

I know that NSTimer is stopped by [MyTimerName invalidate]; method but I don't know how to pause it and again starts with last stoped time?

Upvotes: 2

Views: 1865

Answers (6)

Bhavin Ramani
Bhavin Ramani

Reputation: 3219

- (IBAction)btn_start:(id)sender
{
    if ([startpause.titleLabel.text isEqualToString:@"Start"])
{
    [startpause setTitle:@"Pause" forState:UIControlStateNormal];
    [startpause setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    if (!_myTimer)
    {
        _myTimer = [self createTimer];
    }
    [self.viewww setHidden:NO];
    [self.shuffle_out setUserInteractionEnabled:YES];
    [self.viewww setUserInteractionEnabled:YES];
}
else if ([startpause.titleLabel.text isEqualToString:@"Pause"])
{
    [startpause setTitle:@"Start" forState:UIControlStateNormal];
    [startpause setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    if (!_currentTimeInSeconds)
    {
        _currentTimeInSeconds = 0 ;
    }
    [_myTimer invalidate];
    [self.shuffle_out setUserInteractionEnabled:NO];
    [self.viewww setHidden:YES];
    [self.viewww setUserInteractionEnabled:NO];
}
}

- (NSTimer *)createTimer
{
    return [NSTimer scheduledTimerWithTimeInterval:1.0
                                        target:self
                                      selector:@selector(timerTicked:)
                                      userInfo:nil
                                       repeats:YES];
}
- (NSString *)formattedTime:(int)totalSeconds
{
    int seconds = totalSeconds % 60;
    int minutes = (totalSeconds / 60) % 60;

    return [NSString stringWithFormat:@"%02d:%02d", minutes, seconds];
}
- (void)timerTicked:(NSTimer *)timer
{
    _currentTimeInSeconds++;
    self.lbl_timer.text = [self formattedTime:_currentTimeInSeconds];
    if ([lbl_timer.text isEqualToString:@"01:00"])
{
    [_myTimer invalidate];
    //lbl_timer.text=@"00:00";
    [startpause setTitle:@"Start" forState:UIControlStateNormal];
    [startpause setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    UIAlertView *alrt=[[UIAlertView alloc]initWithTitle:nil message:@"⏰...Game Over...⌛️" delegate:self cancelButtonTitle:nil otherButtonTitles:@"Ok", nil];
    [alrt show];
   }
}

This is working like charm for me...

Upvotes: 1

luckyShubhra
luckyShubhra

Reputation: 2751

In Objective-C Declare two global var as

int time;
NSTimer *timer;

- (IBAction)start:(id)sender
 {
   timer=[NSTimer scheduledTimerWithTimeInterval:1 target:self  selector:@selector(increaseTimer) userInfo:nil repeats:YES];
 }

- (IBAction)pause:(id)sender
{
  [timer invalidate];
}
- (IBAction)reset:(id)sender {
     [timer invalidate];
     time = 0;
     _lbl_tmer.text=@"0";
 }
  -(void)increaseTimer {
   time++;
    NSString *str=[NSString stringWithFormat:@"%d",time];
    _lbl_tmer.text = str;
 }

In Swift

Declare two global var

var timer = NSTimer()

var time = 0

Thenceforth manipulate them accordingly

@IBOutlet var timerLabel: UILabel!

func increaseTimer() {

    time++

    timerLabel.text = "\(time)"

}

@IBAction func play(sender: AnyObject) {

    timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("increaseTimer"), userInfo: nil, repeats: true)

}

@IBAction func pause(sender: AnyObject) {

    timer.invalidate()

}

@IBAction func reset(sender: AnyObject) {

    timer.invalidate()

    time = 0

    timerLabel.text = "0"

}

Happy Coding.. :)

Upvotes: 0

Abhinav
Abhinav

Reputation: 38162

There is no direct way of doing this. You can materialise this in below fashion:

Step 1 : Create properties to hold your timer, a count timer and a counter to count the time elapsed

@property (nonatomic, assign) NSInteger timerCount;
@property (nonatomic, strong) NSTimer *myCountTimer;
@property (nonatomic, strong) NSTimer *myTimer;

Step 2 : Start your timer, count timer and implement the timer handlers:

- (void)startTimer {
    self.myCountTimer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self  selector:@selector(countTimer:) userInfo:nil repeats:NO];

    self.myTimer = [NSTimer scheduledTimerWithTimeInterval:60.0f target:self  selector:@selector(fireTimer:) userInfo:nil repeats:NO];
}


- (void)countTimer:(NSTimer *)inTimer {
    self.timerCount += 1;
}


- (void)fireTimer:(NSTimer *)inTimer {
    // Timer is fired.
}

Step 3 : Implement play/pause timers:

- (void)pauseTimer {
    [self.myTimer invalidate];
    self.myTimer = nil;
}

- (void)resumeTimer {
    if(self.myTimer) {
        [self.myTimer invalidate];
        self.myTimer = nil;
    }

    NSInteger remainingTime = 60 - self.timerCount;

    self.myTimer = [NSTimer scheduledTimerWithTimeInterval:remainingTime target:self  selector:@selector(fireTimer:) userInfo:nil repeats:YES];
}

Upvotes: 0

Fahim Parkar
Fahim Parkar

Reputation: 31637

There is no event called pause in NSTimer

To achieve pause and resume function below is what you can do.

  1. When you click start, notice the current time.

  2. When you click pause, notice the current time.

  3. When you click start again, you will create NSTimer with time remaining from Step 2 time - Step 1 time.

Hope you got idea on what needs to be done...

Upvotes: 2

Waseem Ahmad
Waseem Ahmad

Reputation: 43

The only way to invalidate and re create NSTimer object

Upvotes: 0

Mehul
Mehul

Reputation: 3178

Create Object Like..

NSTimer *timer;

To Stop Timer

 if (timer)
    {
        [timer invalidate];
        timer = nil;
    }

To Start Timer

timer=[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(percentageUpdate) userInfo:nil repeats:YES];

other way you can also cancel in viewDidDisappear Method

- (void) viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    if (timer)
    {
        [timer invalidate];
        timer = nil;
    }    
}

Upvotes: 0

Related Questions