How can i start an NSTimer when a user clicks a button?
EDIT:i had the code working and everything, but i put the code to hide the button above the NSTimer code, and when i placed it below the NSTimer code it worked!
The line of code to start a timer is (read the docs here) :
[NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:#selector(timerFired:)
userInfo:nil
repeats:nil];
This will call the method timerFired: after 1 second i.e.
- (void)timerFired:(NSTimer *)timer {
NSLog(#"timer : %# has gone off", timer);
}
To get this to trigger from a button, you need this method in your .h file :
- (IBAction)buttonPressed:(id)sender;
and in your .m file, detect the button press like this :
- (IBAction)buttonPressed:(id)sender {
NSLog(#"Button's been pressed!");
}
Then, in interface builder connect the button's 'Toiuch Up Inside' action to this method.
Schedule it in the IBAction of the button. Check NSTimer Class Reference to know how to use timers.
You have to insert the command of[NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:#selector(timerFired:)
userInfo:nil
repeats:nil];
inside the buttonclick. Then only you could make the NStimer run after the button click (if you want to run the timer after the button click event )
Related
I have a lot of search about this and found many solution but no one works in my case.
i am using a NSTimer and activate it from a button click here its work fine . Now i invalidate timer on second button click and start it again on third button click but on third button click my timer not works. Can anyone tell me what is the wrong with me.
Code which i am using.
button1 click :
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(updateCountdown) userInfo:nil repeats:YES];
button2 click :
if (timer != nil && [timer isValid])
{
[timer invalidate];
timer=nil;
}
button3 click :
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(updateCountdown) userInfo:nil repeats:YES];
now on click on button3 timer not working.
by looking at your code . It must work . do couple of trials:
Check the your 3 rd button click event is being called or not .
Check if you are doing timer=nil , [timer invalidate]; somewhere else .
I've implemented a repeated task on button (UIButton) hold with the code from another Stack Overflow thread ( UIButton Touch and Hold ).
For various reasons, I'd like a repeat delay. definition of repeat delay
I can't quite wrap my head around how to do this however. I am relatively new to coding for the iPhone.
Inspired in the code you suggested you can go for something like this:
Make an NSTimer that will start up when the button is pressed and fire a method every x seconds.
Header (.h):
// Declare the timer and the needed IBActions in interface.
#interface className {
NSTimer * timer;
}
-(IBAction)theTouchDown(id)sender;
-(IBAction)theTouchUpInside(id)sender;
-(IBAction)theTouchUpOutside(id)sender;
// Give the timer properties.
#property (nonatomic, retain) NSTimer * timer;
Implementation file (.m):
// Synthesize the timer
// ...
Make an IBAction for "Touch Down" to start the timer that will fire the action method every 2 seconds. Then make another IBAction for "Touch Up Inside" and "Touch Up Outside" to invalidate the timer.
For example:
-(IBAction)theTouchDown {
self.timer = [NSTimer scheduledTimerWithTimeInterval:2.0
target:self
selector:#selector(action:)
userInfo:nil
repeats:NO];
}
-(IBAction)theTouchUpInside {
[self.timer invalidate];
self.timer = nil;
}
-(IBAction)theTouchUpOutside {
[self.timer invalidate];
self.timer = nil;
}
Then in that method fired by the NSTimer do whatever you need:
-(void)action:(id)sender {
// ...
}
I have NSTimer in ViewController Class.. And all the methods for NStimer are in that class.. My NSTimer is working properly for play and pause... When i press home button on iPhone also the timer is working properly(it starts running from the time where the application enters into background when the application enters into foreground)... In my application i am rising an alert quickly when my application enters into foreground(UIAlertview in application didEnterForeGround). Here my NSTimer is running when the alert is on the screen(didn't give response to alert).. I want stop the NSTimer Upto the User responding to my alert... After that I want to start the NSTimer... How Can i do that...? Please help me... Thanks in Advance... I want call the NSTimer methods from Appdelegate.m file... Iam calling these methods properly... And the methods in ViewController are called.. But the action is Not Performing... For the Same method when call from viewController class it is working...
enter code here
ViewController.h
+(ExamViewController *)evcInstance;
ViewController.m
ExamViewController *evc = nil;
#implementation ExamViewController
+(ExamViewController *)evcInstance
{
if(!evc)
{
evc = [[ExamViewController alloc] init];
}
return evc;
}
- (void)onStartPressed
{
stopwatchtimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:#selector(updateTimer:) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:stopwatchtimer forMode:NSRunLoopCommonModes];
resume.hidden = YES;
resume.enabled=NO;
pause.hidden = NO;
pause.enabled=YES;
}
- (void)onStopPressed
{
[stopwatchtimer invalidate];
stopwatchtimer = nil;
pause.hidden = YES;
pause.enabled=NO;
resume.hidden = NO;
resume.enabled=YES;
}
Appdelegate.m
- (void)applicationWillEnterForeground:(UIApplication *)application
{
[[ExamViewController evcInstance] onStopPressed];
NSLog(#"applicationWillEnterForeground");
if(viewCalled ==YES)
{
UIAlertView *alertview=[[UIAlertView alloc]initWithTitle:#"" message:#"DO! You Want To continue" delegate:self cancelButtonTitle:#"YES" otherButtonTitles:#"NO", nil];
[alertview show];
[alertview release];
}
/*
Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
*/
}
a few things:
1) It looks like an incomplete singleton design. If you really want a singleton, refer to a post like this one.
2) No need to add stopwatchtimer to the current run loop. The scheduledTimerWithTimeInterval method schedules it for you.
3) I don't see where you declare stopwatch timer, but be sure to declare it as a retained property (or strong in ARC).
4) To stop the timer, just call [stopwatchtimer invalidate]; To restart it, re-instantiate and overwrite the old one using the same scheduledTimerWithTimeInterval class method that you called originally.
5) To do anything when an alert view completes, implement the delegate method:
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
So you can invalidate the timer before presenting the alert, then rebuild it when you get notified the alert is finished.
I have a timer which i am using in my application..
In my application ,I have two views. On the first view i have added a button and a progress bar and i have used a timer for progress bar.
User can move to next view either on clicking the button or wait for progress bar to complete..
If the progress bar is completed the user will be drawn to next view..
Here, is my question How to stop timer which have no name like...
[NSTimer scheduledTimerWithTimeInterval:0.0005 target:self selector:#selector(onTimer) userInfo:nil repeats:YES];
Because of not stopping the timer in the first view if the user waits for progress bar to complete,the things in the next view will not work...
Store the returned NSTimer from scheduledWithTimeInterval::::: and later call invalidate on it to stop the timer.
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.0005 target:self selector:#selector(onTimer) userInfo:nil repeats:YES];
// This will stop the tmer
[timer invalidate];
To stop timer you need to use
[timer invalidate];
I have a timer that launches in viewDidLoad that looks like this
[NSTimer scheduledTimerWithTimeInterval:0.001f target:self selector:#selector(Dragon:) userInfo:nil repeats:YES];
I want to be able to change my Interval with a variable. However, any time I try to place a variable where the 0.001f is I get errors... any ideas?
I have an app that does exactly what you are asking. I allow the user to change the speed of the timer within the app so I need to make that speed a variable. Here's how I did it:
I create a timer property on my main view controller class.
I initialize the timer when the main view controller class loads.
Each time thereafter, I invalidate my timer and reset it when the value changes.
Some snippets from inside of my main view controller .m file:
//How often to switch views (float)
#define kInterval [[NSUserDefaults standardUserDefaults] integerForKey:#"interval"]
- (void) viewDidAppear:(BOOL)animated{
[self setTimer];
}
- (void) setTimer{
[self.timer invalidate];
[self setTimer: [NSTimer scheduledTimerWithTimeInterval:kInterval target:self selector:#selector(timerFired) userInfo:nil repeats:YES]];
}
Is the app returning from a background process? If so, you may need to re-set the timer. You might also want to peek at CADisplayLink: http://developer.apple.com/library/ios/#documentation/QuartzCore/Reference/CADisplayLink_ClassRef/Reference/Reference.html%23//apple_ref/doc/uid/TP40009031
#King Popsicle you can take help of this method
(void)applicationWillEnterForeground:(UIApplication *)application OR
(void)applicationDidBecomeActive:(UIApplication *)application
You can fix the things in this method regarding the timer values :)