I'm using NSTimer to display seconds on a label while recording.
I'm starting the timer when the record button is tapped and stopping it when the stop button is tapped.
When I tap the play button the timer is not restarting.
-(void)startTimer
{
playTimer = [NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:#selector(timerController)
userInfo:nil
repeats:YES];
}
- (NSString*)getTimeStr : (int) secondsElapsed
{
seconds = secondsElapsed % 60;
int minutes = secondsElapsed / 60;
int hours = secondsElapsed/3600;
return [NSString stringWithFormat:#"%02d:%02d:%02d", hours, minutes, seconds];
}
- (void)timerController{
seconds++;
[[self timeLabel] setText:[self getTimeStr:(seconds)]];
}
- (IBAction)recordTapped:(id)sender {
[self startTimer];
}
- (IBAction)stopTapped:(id)sender {
[playTimer invalidate];
playTimer=nil;
_timeLabel.text=#"00:00:00";
}
- (IBAction)playTapped:(id)sender {
[self startTimer];
}
As mentioned in the comments, there are two bugs around:
Bug #1
You should always reset the variable seconds to 0 before restarting the timer (probably reset it at the 1st line of startTimer)
Bug #2
The variable seconds is overwritten by the 1st line of getTimeStr function. You should replace seconds with int sec and for the return line, replace seconds with sec.
- (void)resetTimer {
if(playTimer) {
[playTimer invalidate];
playTimer = nil;
}
}
You should call resetTimer method every time before startTimer again.
Related
A strange situation:
If I started my Timer again and again without stopping it first, it will count increasingly fast. I guess it is because it starts multiple timers now?
However, when I finally want to stop it, it cannot be stopped...keep going forever.
(Maybe for design consideration, I should disable users from pressing start again, but I'm wondering what is really behind this and why the timer can't be stopped.)
- (IBAction)Start:(id)sender {
countInt = 0;
self.Time.text = [NSString stringWithFormat:#"%i", countInt];
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(countTimer) userInfo:nil repeats:YES];
}
- (IBAction)Stop:(id)sender {
[timer invalidate];
}
- (void) countTimer {
countInt += 1;
self.Time.text = [NSString stringWithFormat:#"%i", countInt];
}
#end
The simple solution is to call stop at the beginning of the start method.
Note that in stop you should also set timer = nil;
Assuming there is a property timer
#property NSTimer *timer;
the most reliable way to start and stop the timer only once respectively is to create two methods.
- (void)startTimer
{
if (self.timer == nil) {
self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:#selector(countTimer)
userInfo:nil
repeats:YES];
}
}
- (void)stopTimer
{
if (self.timer != nil) {
[self.timer invalidate];
self.timer = nil;
}
}
Both methods perform a check, so the timer can't be restarted while it's running and vice versa.
Now just call the methods in the start/stop IBActions (the names should start with a lowercase letter).
- (IBAction)Start:(id)sender {
countInt = 0;
self.Time.text = [NSString stringWithFormat:#"%i", countInt];
[self startTimer];
}
- (IBAction)Stop:(id)sender {
[self stopTimer];
}
The benefit is pressing Start has no effect when the timer is already running.
When you hit 'start' multiple times you are creating multiple timers. So you are getting multiple timers firing and executing your timer callback. In this timer callback you increment counters. Since there are many timers now, they are all incrementing your counter, hence explaining your rapid increase in the counter.
You can allow the user to tap Start twice, as long you can define what happens when you hit Start while the timer is already going. But you definitely need to invalidate the old timer before creating a new one.
- (IBAction)Start:(id)sender {
...
// Stop previous timer before creating a new timer.
if (timer != nil) {
[timer invalidate]
}
...
}
My timer does not stop even if i am doing "invalidate" and "nil" after reading other links. My code is as below:
#property(nonatomic,strong) NSTimer *mytimer;
- (void)viewDidLoad {
[self performSelectorOnMainThread:#selector(updateProgressBar:) withObject:nil waitUntilDone:NO];
<do some other work>
}
- (void) updateProgressBar :(NSTimer *)timer{
static int count =0;
count++;
NSLog(#"count = %d",count);
if(count<=10)
{
self.DownloadProgressBar.progress= (float)count/10.0f;
}
else{
NSLog(#"invalidating timer");
[self.mytimer invalidate];
self.mytimer = nil;
return;
}
if(count <= 10){
NSLog(#"count = %d **",count);
self.mytimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:#selector(updateProgressBar:) userInfo:nil repeats:YES];
}
}
1) The timer goes on infinetly even when invalidating timer else condition is hit after count >10 and count keeps on incrementing.
2) i want to do this on a non-main thread . i want to continue in viewdidload() after starting the timer. How to do this ?
I visited other links on SO, all i understood was to call invalidate and nil on timer pointer. I am still facing problems. Could anyone tell me what i am missing here and what i can i do to run the updateProgressBar on background thread and update the progress bar ?
don't need to schedule a timer each time, schedule it once and timer will fire every second for example u can do like below,
- (void)viewDidLoad
{
[super viewDidLoad];
[self performSelectorOnMainThread:#selector(startTimerUpdate) withObject:nil waitUntilDone:NO]; //to start timer on main thread
}
//hear schedule the timer
- (void)startTimerUpdate
{
self.mytimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:#selector(updateProgressBar:) userInfo:nil repeats:YES];
}
- (void) updateProgressBar :(NSTimer *)timer{
static int count =0;
count++;
NSLog(#"count = %d",count);
if(count<=10)
{
//self.DownloadProgressBar.progress= (float)count/10.0f;
NSLog(#"progress:%f",(float)count/10.0f);
}
else
{
NSLog(#"invalidating timer");
[self.mytimer invalidate];
self.mytimer = nil;
return;
}
if(count <= 10){
NSLog(#"count = %d **",count);
}
}
I think you are scheduling timer multiple time. I think 10 time. just schedule time one time or if require many time then invalidate it that many time as schedule.
Update according to comment : Schedule timer from viewdidload and addobserver means notification on task. when your task will completed invalidate timer. and update your progress in selector method of timer so when you invalidate it it will automatically stop progress bar.
Second thing : you should invalidate timer before moving another viewcontroller also because this objects remains live untill invalidate.
Hope this will hellp :)
I created a timer, and was wondering if it is at all possible to make the timer go slower when it reaches a certain second: 1..2..3..4..4.1..4.2.
For example, the timer is increasing by 1 second, then at 4 seconds, the time slows down showing milliseconds.
if(i = 4) {
}
It depends on what you want.
Of course, you can't slow down the time, but you can simulate it.
For example, you check how much time has already passed. If it is 1, 2, 3 seconds, you NSLog 1, 2, 3. Then when 4 seconds has passed, you start logging milliseconds.
E.g.
if (i < 4) {
NSLog(#"%d", i);
} else {
NSLog(#"4.%d", i - 4);
}
Sure, logging can be substituted with whatever you need.
P.S. The answer is in Objective-C, but that changes nothing.
You can use a solution like this:
Declare a float to register your time and a NSTimer to perform the action.
#property NSTimer *timer;
#property float time;
Call startTimer to start the actions.
- (void) startTimer {
self.timer = [NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:#selector(secondsAction)
userInfo:nil
repeats:YES];
}
- (void) secondsAction {
self.time += 1;
NSLog(#"%d", (int)self.time);
if(self.time == 4) {
[self.timer invalidate];
self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1
target:self
selector:#selector(milisecondsAction)
userInfo:nil
repeats:YES];
}
}
- (void) milisecondsAction {
self.time += 0.1;
NSLog(#"%.1f", self.time);
}
I make one 30:00 min countdown timer, now when I load next page and back on first page my timer is on but label which show time it's stopped.
Any idea for that when I come on first page and my timer is on and start at same point, in short I need run my timer in background.
This is the code which I use in same view controller where the timer is, but it's not working.
- (void)viewWillDisappear:(BOOL)animated
{
[Timecount invalidate];
}
-(void)viewDidAppear:(BOOL)animated
{
// [self countdownTimer];
}
-(void)viewWillAppear:(BOOL)animated
{
[self countdownTimer];
}
-(void)countdownTimer
{
secondsLeft = hours = minutes = seconds = 0;
if([Timecount isValid])
{
}
Timecount = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:#selector(updateCounter:) userInfo:nil repeats:YES];
}
Is this the right way to check AVAudioPlayer's current playback time.
[audioPlayer play];
float seconds = audioPlayer.currentTime;
float seconds = CMTimeGetSeconds(duration);
How I can code after
[audioPlayer play];
that when currentTime is equal to 11 seconds then
[self performSelector:#selector(firstview) withObject:nil];
and after firstview when currentTime is equal to 23 seconds
[self performSelector:#selector(secondview) withObject:nil];
You could set up a NSTimer to check the time periodically. You would need a method like:
- (void) checkPlaybackTime:(NSTimer *)theTimer
{
float seconds = audioPlayer.currentTime;
if (seconds => 10.5 && seconds < 11.5) {
// do something
} else if (seconds >= 22.5 && seconds < 23.5) {
// do something else
}
}
Then set up the NSTimer object to call this method every second (or whatever interval you like):
NSTimer *myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:#selector(checkPlaybackTime:)
userInfo:nil
repeats:YES];
Check the NSTimer documentation for more details. You do need to stop (invalidate) the timer at the right time when you're through with it:
https://developer.apple.com/documentation/foundation/nstimer
EDIT: seconds will probably not be exactly 11 or 23; you'll have to fiddle with the granularity.