6

I am developing a QuiZ app. It needs a countdown timer, In that I want to start a timer at 75:00.00 (mm:ss.SS) and decrease it to 00:00.00 (mm:ss.SS) by reducing 1 millisecond. I want to display an alert that Time UP! when time reaches to 00:00.00 (mm:ss.SS).

I am displaying the time by following below link

Stopwatch using NSTimer incorrectly includes paused time in display

Community
  • 1
  • 1
SriKanth
  • 459
  • 7
  • 27

2 Answers2

13

Here is a simple solutions to your problem.

Declarations

@interface ViewController : UIViewController
{
    IBOutlet UILabel * result;      
    NSTimer * timer;                
    int currentTime;
}

- (void)populateLabelwithTime:(int)milliseconds;
-(IBAction)start;
-(IBAction)pause;
@end

Definition

- (void)viewDidLoad
{
    [super viewDidLoad];

    currentTime = 270000000; // Since 75 hours = 270000000 milli seconds


}

-(IBAction)start{
   timer = [NSTimer scheduledTimerWithTimeInterval:.01 target:self selector:@selector(updateTimer:) userInfo:nil repeats:YES];

}
-(IBAction)pause{
    [timer invalidate];

}
- (void)updateTimer:(NSTimer *)timer {
    currentTime -= 10 ;
    [self populateLabelwithTime:currentTime];
     }
- (void)populateLabelwithTime:(int)milliseconds {
    int seconds = milliseconds/1000;
    int minutes = seconds / 60;
    int hours = minutes / 60;

    seconds -= minutes * 60;
    minutes -= hours * 60;

   NSString * result1 = [NSString stringWithFormat:@"%@%02dh:%02dm:%02ds:%02dms", (milliseconds<0?@"-":@""), hours, minutes, seconds,milliseconds%1000];
    result.text = result1;

}
Shaheen M Basheer
  • 1,010
  • 6
  • 11
  • Hai it works fine with some changes... i have scroll view in which i am displaying the time.. If i Drag the scroll view the time is not calculating (in the background also)... what i have to do...? – SriKanth Apr 21 '12 at 12:33
  • 1
    Add this code to enable timer during scroll .................................................................................. -(IBAction)start{ timer = [NSTimer scheduledTimerWithTimeInterval:.01 target:self selector:@selector(updateTimer:) userInfo:nil repeats:YES]; [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes]; } – Shaheen M Basheer Apr 22 '12 at 06:15
3

Use following code for reducing timer.

double dblRemainingTime=60; //1 minute

if(dblRemainingTime >0)
{
     dblRemainingTime -= 1;
     int hours,minutes, seconds;
     hours = dblRemainingTime / 3600;
     minutes = (dblRemainingTime - (hours*3600)) / 60;
     seconds = fmod(dblRemainingTime, 60);  
     [lblRemainingTime setText:[NSString stringWithFormat:@"%02d:%02d",minutes, seconds]];
}
else
      alert('Time up buddy');
Janak Nirmal
  • 22,706
  • 18
  • 63
  • 99