Search This Blog

Oct 18, 2010

How to create a countdown timer in iPhone app.

This code is used to create a countdown timer in iPhone app.

1. Code for .h file.

@interface UIMyContoller : UIViewController {

    NSTimer *timer;
    IBOutlet UILabel *myCounterLabel;
}

@property (nonatomic, retain) UILabel *myCounterLabel;
-(void)updateCounter:(NSTimer *)theTimer;
-(void)countdownTimer;

@end

2. Code for .m file.

@implementation UIMyController
@synthesize myCounterLabel;

int hours, minutes, seconds;
int secondsLeft;

- (void)viewDidLoad {
    [super viewDidLoad];
   
    secondsLeft = 16925;
    [self countdownTimer];
}

- (void)updateCounter:(NSTimer *)theTimer {
    if(secondsLeft > 0 ){
        secondsLeft -- ;
        hours = secondsLeft / 3600;
        minutes = (secondsLeft % 3600) / 60;
        seconds = (secondsLeft %3600) % 60;
        myCounterLabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];
    }
    else{
        secondsLeft = 16925;
    }
}

-(void)countdownTimer{
   
    secondsLeft = hours = minutes = seconds = 0;
    if([timer isValid])
    {
        [timer release];
    }
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 
    timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateCounter:) userInfo:nil repeats:YES];
    [pool release];
}

6 comments:

  1. this is great but could it work with button pressed action?

    ReplyDelete
  2. I'm getting invalid suffix "oftarget.self" on floating constant. Any idea on what that means?

    ReplyDelete
  3. that is not "of target", its 1.0f. here f is for float.

    ReplyDelete
  4. I just tried an application on my iPhone Clear Timer App, it is user friendly, its nice and cool.

    ReplyDelete
  5. what is the logic behind the calclulation of 16925.
    can any one explain it...???

    ReplyDelete
    Replies
    1. 16925 is in seconds, you can give it any value, when you want to start the alarm.

      Delete