Vamshi
Vamshi

Reputation: 1

How can i create 30 minute count down timer in cocos2d like candy crush lives.

Hi Friends i need count down timer for add lives every 30 minutes. So i created a count down timer but it is running on that call only. Here i need the timer run globally. If aplication in back ground or termnate any body help me.

This is my code

   int hours, minutes, seconds;
    NSTimer *timer;


- (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];
    [self removeChild:Liveslable];
    Liveslable=[CCLabelTTF labelWithString:[NSString stringWithFormat:@"lives left in  %02d:%02d minuts",minutes, seconds] fontName:@"ArialMT" fontSize:25];
    Liveslable.position=ccp(winSize.width/2, winSize.height/2-140);
    [self addChild:Liveslable];
}
else{
    secondsLeft = 1800;
}
}

-(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];
}

Upvotes: 0

Views: 790

Answers (1)

Sebastian
Sebastian

Reputation: 314

It is not appropriate to use the NSTimer in this case. You cannot execute code in the background, with good reason (imagine if the user quits the process, or turns the device off). Instead you should look into storing the timestamp at which a life has been given and then calculate the timestamp for when the next life should be given.

You can save the time to NSUserDefaults like this:

float timeStamp = [[NSDate date] timeIntervalSince1970] * 1000; // Milliseconds 
[[NSUserDefaults standardUserDefaults] setFloat:timeStamp forKey:@"lastTimeStamp"];

And retrieve the previous timestamp like this:

float lastTime = [[NSUserDefaults standardUserDefaults] floatForKey:@"lastTimeStamp"];

Whenever the user opens the application you should perform your calculations and give lives accordingly. This can be done in applicationWillEnterForeground: in the AppDelegate.m

You can use your NSTimer to check if the next timestamp matches the NSDate-time while the app is running.

Upvotes: 1

Related Questions