How to make a UILabel that constantly updates in Objective-C - iphone

I'm looking to make a UILabel display the current progress of a timer. Right now to get the current time left I call [timer1 timeLeft]; which returns an int. In this way I can update the label ONCE, at one instant. In what way can I update the label (mainLabel) constantly so that it is always displaying the current timer progress while being somewhat resource efficient?
Thanks for all your help!

Use following code for Countdown timer.
dblElapsedSeconds=0.0; //Declare this in header
tmrElapsedTime = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:#selector(updateElapsedTime) userInfo:nil repeats:YES]; //Declare timer variable in header
-(void)updateElapsedTime
{
dblElapsedSeconds += 1;
//double seconds = [[NSDate date] timeIntervalSinceDate:self.startTime];
int hours,minutes, lseconds;
hours = dblElapsedSeconds / 3600;
minutes = (dblElapsedSeconds - (hours*3600)) / 60;
lseconds = fmod(dblElapsedSeconds, 60);
[lblTimeElapsed setText:[NSString stringWithFormat:#"%02d:%02d",minutes, lseconds]];
}

Related

NSTimer in background

I am very new in Iphone Development. I have an issue . I am using a NSTimer which update a UiLabel in every second. now i have two problem :
when my app goes in background and after it when i open app . app goes hangs.
if i goes next or back on other ui screen then wen i comes on timer screen then my label again shows 0.
can anyone help me.
code which i am using :
timer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target:self selector:#selector(updateCountdown) userInfo:nil repeats: YES];
-(void) updateCountdown
{
secondsLeft--;
//nits testing
if(secondsLeft == 1)
{
[self.view addSubview:recipePage6View.view];
}
if (secondsLeft<0)
{
[timer invalidate];
timer=nil;
lblDisplayTimer.text =#"00:00:00";
}
else
{
hours = secondsLeft / 3600;
minutes = (secondsLeft % 3600) / 60;
seconds = (secondsLeft %3600) % 60;
lblDisplayTimer.text = [NSString stringWithFormat:#"%02d:%02d:%02d", hours, minutes, seconds];
//lblDisplayTimer.text = [NSString stringWithFormat:#"%02d:%02d",minutes,seconds];
}
}
You need to set up a special background timer task and not have an NSTimer on the main run loop which gets suspended in background. The documentation on how to do this is here

NSTimer Restarting

I have CountDown timer like below:
- (void)updateCounterLabel:(NSTimer *)theTimer {
if(secondsLeft > 0 ){
secondsLeft -- ;
hours = secondsLeft / 3600;
minutes = (secondsLeft % 3600) / 60;
seconds = (secondsLeft %3600) % 60;
countDownLabel.text = [NSString stringWithFormat:#"%02d:%02d:%02d", hours, minutes, seconds];
}
else{
secondsLeft = timeInterval;
}
-(void)countdownTimer {
if([timer isValid]){
[timer invalidate];
timer = nil;
}
timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:#selector(updateCounterLabel:) userInfo:nil repeats:YES];
}
----My problem is that every time recall this timer it increments like this : secondLeft-3 , secondLeft -5 ,secondLeft - 7..................
Each time my view loads, i create a new timer, but the old ones still exist.in my timer's action method, i am decrementing an index variable that keeps track of the seconds, and each timer runs that method every time it fires. So, if i have three timers, the index will decrements by three each time.
For example:
First Load: 60, 59, 58...
Second Load: 60, 58, 56...
Third Load: 60, 57, 54...
Question : How can i restart or recreate a timer without above problem? somebody help me out pls.
The
timer = [NSTimer scheduledTimerWithTimeInterval:...];
call retains the target (the view controller) while the timer is running,
so that the view controller
is never deallocated and the timer continues to run even if the view controller
is popped off the navigation stack or dismissed.
Therefore, if the view is loaded again, you have two instances of the view controller and
therefore two timers, which both decrement the same global variable secondsLeft.
This hopefully explains why the value is decremented by two each second.
As a solution, you can create the timer in viewWillAppear, and invalidate it
in viewWillDisappear.

iPhone Countdown Timer For a Selected Duration

I wish to create a countdown timer in my app in such a way that I can give a certain duration (like 15 minutes or 15:00) and it starts on an action.
I also need for that countdown timer to take elapsed time duration and total time duration information from an external web service and start the countdown for the remaining time.
This is actually for a quiz application where the user will be presented with a series of questions and the timer will be placed on the question screen (for the whole quiz and not for only one question). The user can set the duration for the quiz and the countdown timer will begin as soon as the user start taking the quiz. There is also a pause functionality where user can pause the test and the information of time elapsed and total time duration will be registered in a web-service. The user can resume the quiz anytime with the countdown timer starting right from the time it was paused (taking this information from the web-service, that is).
Thanks in advance.
PS: To be honest, I had no idea on how to go about it. There was too much of confusion on what format will the time be stored over in the web-service and a lot of other stuff like if the program will go forward after the NSTimer is running in a loop etc. So you know what I mean. Yes, NSTimer does solve the problem as Alex told and provided with a sample code as well.
Look at the docs for NSTimer.
Generally, you would create an NSTimer which calls a method every second, like so:
NSTimer *theTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(tick) userInfo:nil repeats:YES];
Then in tick, you would decrement a variable holding the time remaining, and update a label on the display.
Also, if you want some working sample code, check out my little countdown app on GitHub.
Try these codes, I have already implemented it in my App. Best for resend OTP type functionalities.
int secondsLeft;
int hours, minutes, seconds;
secondsLeft = 60;
[self countdownTimer];
-(void)countdownTimer {
// secondsLeft = hours = minutes = seconds = 0;
timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:#selector(updateCounter:) userInfo:nil repeats:YES];
}
- (void)updateCounter:(NSTimer *)theTimer {
if(secondsLeft > 0 ) {
secondsLeft -- ;
hours = secondsLeft / 3600;
minutes = (secondsLeft % 3600) / 60;
seconds = (secondsLeft %3600) % 60;
labelSeconds.text = [NSString stringWithFormat:#"%02d seconds left.",seconds];
} else {
[timer invalidate];
return;
}
}

Wait for random amount of time, then start updating elapsed time in a UILabel (iPhone)

I'm trying to implement a button that starts a timer after a random period of time (between 0-10s). While the timer is running it should update a label every 0.005s to show how much time has elapsed. The problem i'm having is 2-fold:
I'm not sure how to get the label to update with the elapsed time every 0.005s.
I'm having trouble getting the app to wait the random amount of time before starting timer. At present I'm using sleep(x) however it seems to cause the app to ignore all the other code in the if statement and causes the button image to freeze up (i.e. it looks like its still clicked).
Here is the code I have so far...
- (IBAction)buttonPressed:(id)sender
{
if ([buttonLabel.text isEqualToString:#"START"])
{
buttonLabel.text = #" "; // Clear the label
int startTime = arc4random() % 10; // Find the random period of time to wait
sleep(startTime); // Wait that period of time
startTime = CACurrentMediaTime(); // Set the start time
buttonLabel.text = #"STOP"; // Update the label
}
else
{
buttonLabel.text = #" ";
double stopTime = CACurrentMediaTime(); // Get the stop time
double timeTaken = stopTime - startTime; // Work out the period of time elapsed
}
}
If anyone has any suggestions on..
A) How to get the label to update with the elapsed time.
or
B) How to fix the 'delay' period from freezing up the app
... it would be really helpful as I'm pretty much stumped at this point. Thanks in advance.
You should use an NSTimer to do this. Try the code:
- (void)text1; {
buttonLabel.text = #" ";
}
- (void)text2; {
buttonLabel.text = #"STOP";
}
- (IBAction)buttonPressed:(id)sender; {
if ([buttonLabel.text isEqualToString:#"START"]) {
int startTime = arc4random() % 10; // Find the random period of time to wait
[NSTimer scheduledTimerWithTimeInterval:(float)startTime target:self selector:#selector(text2:) userInfo:nil repeats:NO];
}
else{
// I put 1.0f by default, but you could use something more complicated if you want.
[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:#selector(text1:) userInfo:nil repeats:NO];
}
}
I'm not exactly sure how you want to update label based on the time, but if you post more code, or give an example, I'll post the code on how to do that, but it would just be using an NSTimer as well. Hope that Helps!
The answer to A could be:
Once the random amount of time has passed, (#MSgambel has a good suggestion), then execute:
timer = [NSTimer scheduledTimerWithTimeInterval:kGranularity target:self selector:#selector(periodicallyUpdateLabel) userInfo:nil repeats:YES];
(The above line could go into #MSgambel's -text2 method.)
That will call the -periodicallyUpdateLabel method once every kGranularity seconds, repeatedly. In that method, you could do things like update your label, check for user actions, or end the game if the time is up or some other condition has been met.
And here is the -periodicallyUpdateLabel method:
- (void)periodicallyUpdateView {
counter++;
timeValueLabel.text = [NSString stringWithFormat:#"%02d", counter];
}
You'll have to format the text differently to get what you want. Also, translate from the counter value to time using kGranularity. However, and this is what I found, there is only so many cpu cycles in iOS devices. Trying to go down to microsecond level made the interface sluggish and the time displayed started to drift from the actual time. In other words, you may have to limit your updates of the label to once every one hundredth of a second or tenths. Experiment.

Ios UILabel update performance

in my application i have an UILabel showing a time updated every second.
I have also draggable objects in the screen.
When I hide the label or i stop the timer everything is perfect but when i start the timer the animation performance of dragging objects go down.
I put the UILabel updating in a separate thread but no luck.
I need help friends :)
This is my code:
self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:#selector(onTimer:) userInfo:nil repeats:YES];
-(void) onTimer:(NSTimer *)timer;
{
timeInterval ++;
int hours = (int)timeInterval / 3600;
int minutes = (timeInterval %3600)/ 60;
int seconds = ((timeInterval%3600)%60);
NSString *timeDiff = [NSString stringWithFormat:#"%d:%02d:%02d", hours,minutes,seconds];
[NSThread detachNewThreadSelector:#selector(setText:) toTarget:self.time withObject:timeDiff];
}