Objective C & iOS: running a timer? NSTimer/Threads/NSDate/etc - objective-c

I am working on my first iOS app, and have run in the first snag I have not been able to find a good answer for.
The problem: I have a custom UIGestureRecognizer and have it all wired up correctly, and I can run code for each touch in the #selector after recognition. This has been fine for most things, but it's a little too much input for others.
My goal: To make a timer that triggers at a specified interval to run the logic, and to be able to cancel this at the moment touches are cancelled.
Why I am asking here: There are a lot of possibilities for solutions, but none has stood out as the best to implement. So far it seems like
performSelector (and some variations on this)
NSThread
NSTimer
NSDate
Operation Queues
I think I found some others as well...
From all the research, some form of making a thread seems the route to go, but I am at a loss at which would work best for this situation.
An example of an implementation: an NSPoint is taken every 0.10 seconds, and the distance between the previous and current point is taken. [Taking the distance between every point was yielding very messy results].
The relevant code:
- (void)viewDidLoad {
CUIVerticalSwipeHold *vSwipe =
[[CUIVerticalSwipeHold alloc]
initWithTarget:self
action:#selector(touchHoldMove:)];
[self.view addGestureRecognizer:vSwipe];
[vSwipe requireGestureRecognizerToFail:doubleTap];
}
...
- (IBAction)touchHoldMove:(UIGestureRecognizer *)sender {
if (sender.state == UIGestureRecognizerStateEnded) {
}
if (sender.state == UIGestureRecognizerStateBegan) {
}
//other stuff to do goes here
}

Use an NSTimer
Set it up like this:
theTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:#selector(yourMethodThatYouWantRunEachTimeTheTimerFires) userInfo:nil repeats:YES];
Then when you want to cancel it, do something like this:
if ([theTimer isValid])
{
[theTimer invalidate];
}
Note that in the above example you would need to declare the "theTimer" instance of NSTimer where it will be available to both methods. In the above example the "0.5" means that the timer will fire twice a second. Adjust as needed.

For the sake of completeness, I am adding my final implementation here (not sure this is the way to do it, but here goes)
.h
#interface {
NSTimer *myTimer;
}
#property (nonatomic, retain) NSTimer *myTimer;
.m
#synthesize myTimer;
-------------------------------------------
- (void)viewDidLoad {
//Relevant snipet
CUIVerticalSwipeHold *vSwipe =
[[CUIVerticalSwipeHold alloc]
initWithTarget:self
action:#selector(touchHoldMove:)];
[self.view addGestureRecognizer:vSwipe];
[vSwipe requireGestureRecognizerToFail:doubleTap];
}
-------------------------------------------
- (IBAction)touchHoldMove:(UIGestureRecognizer *)sender {
if (sender.state == UIGestureRecognizerStateEnded) {
//Cancel the timer when the gesture ends
if ([myTimer isValid])
{
[myTimer invalidate];
}
}
}
if (sender.state == UIGestureRecognizerStateBegan) {
//starting the timer when the gesture begins
myTimer = [NSTimer scheduledTimerWithTimeInterval:someTimeIncrement
target:self
selector:#selector(someSelector)
userInfo:nil
repeats:YES];
}
}

Related

How do I set a NSTimer to stop if a certain action is running?

I have a popup in a custom view controller that is presented after 1 minute thanks to my NSTimer.
My NSTimer code:
[NSTimer scheduledTimerWithTimeInterval:60.0f
target:self selector:#selector(methodB:) userInfo:nil repeats:YES];`
The method that reveals the popup
- (void) methodB:(NSTimer *)timer
{
//Do calculations.
[self showPopupWithStyle:CNPPopupStyleFullscreen];
}
I'm trying to set the NSTimer to stop running if the [self showPopupWithStyle:CNPPopupStyleFullscreen]; is currently open, running or active.
Then I would like to start the NSTimer back up again if the popup view controller is NOT open, running or active.
Any help, samples or examples would be greatly appreciated!
My project is written in Objective-C.
EDIT:
I tried the answers in the suggested "possibly similar" answer and it doesn't seem to work for what I am doing. How do I stop NSTimer?
This seems to do the trick.
#property (nonatomic, strong) CNPPopupController *popupController;
- (void)_timerFired:(NSTimer *)timer;
#end
NSTimer *_timer;
- (void)viewDidLoad {
[super viewDidLoad];
if (!_timer) {
_timer = [NSTimer scheduledTimerWithTimeInterval:10.0f
target:self
selector:#selector(_timerFired:)
userInfo:nil
repeats:YES];
}
}
- (void)_timerFired:(NSTimer *)timer {
if ([_timer isValid]) {
[self showPopupWithStyle:CNPPopupStyleFullscreen];
[_timer invalidate];
}
_timer = nil;
NSLog(#"ping");
}
If you want to restart the timer just add this code where you'd like the action to start back up.
if (!_timer) {
_timer = [NSTimer scheduledTimerWithTimeInterval:10.0f
target:self
selector:#selector(_timerFired:)
userInfo:nil
repeats:YES];
}
Hope this helps! :)

Touches are getting noticed twice in objective c

I am implementing session inactivity for my app so that if user is inactive for 30 seconds, then show him a new uiviewcontroller as a formsheet. For touch event, i am using this code
(void)sendEvent:(UIEvent *)event {
[super sendEvent:event];
// Only want to reset the timer on a Began touch or an Ended touch, to reduce the number of timer resets.
NSSet *allTouches = [event allTouches];
if ([allTouches count] > 0) {
// allTouches count only ever seems to be 1, so anyObject works here.
UITouchPhase phase = ((UITouch *)[allTouches anyObject]).phase;
if (phase == UITouchPhaseBegan || phase == UITouchPhaseEnded) {
[[BCDTimeManager sharedTimerInstance]resetIdleTimer];
}
}
}
In BCDTimeManager class which is a singleton class i have implemented resetIdleTimer and idleTimerExceed method
#import "BCDTimeManager.h"
#implementation BCDTimeManager
__strong static BCDTimeManager *sharedTimerInstance = nil;
NSTimer *idleTimer;
NSTimeInterval timeinterval;
+ (BCDTimeManager*)sharedTimerInstance
{
static dispatch_once_t predicate = 0;
dispatch_once(&predicate, ^{
sharedTimerInstance = [[self alloc] init];
NSString *timeout = [[NSUserDefaults standardUserDefaults] valueForKey:#"session_timeout_preference"];
timeinterval = [timeout doubleValue];
});
return sharedTimerInstance;
}
- (void)resetIdleTimer {
if (idleTimer) {
[idleTimer invalidate];
}
idleTimer = nil;
NSLog(#"timeout is %ld",(long)timeinterval);
idleTimer = [NSTimer scheduledTimerWithTimeInterval:timeinterval target:self selector:#selector(idleTimerExceeded) userInfo:nil repeats:true];
}
- (void)idleTimerExceeded {
NSLog(#"idle time exceeded");
[[NSNotificationCenter defaultCenter]
postNotificationName:#"ApplicationTimeout" object:nil];
}
But when i do any touch on the screens, in console, i can see NSLog is printed twice which is causing my NSNOtification action to be triggered twice.
I am not sure what i am doing wrong. Please help me to figure out this.
I figured it out. Code is doing right. I am seeing NSLog twice because of two touch event one touch began and one touch ended. So, this code is correct without any issue. Something is wrong with observers add or remove method. I will look into that

Update UILabel according to NSTimer [duplicate]

This question already has answers here:
Objective-C : NSTimer and countdown
(2 answers)
Closed 9 years ago.
I have a UILabel that I would like to update as a countdown timer. Currently I am using an NSTimer to execute a method when the allotted inactivity time has passed. I found the code for setting up the desired NSTimer from this SO thread. I'm using the example code posted by Chris Miles in one of the view controllers for the application, and the method is executing properly when the idle time reaches the kMaxIdleTimeSeconds.
However I was hoping to take the code example posted by Chris Miles a step further by updating a UILabel in the view controller with the remaining idle time. Should I use a completely separate NSTimer to do this, or is there a way to update UILabel with idle time remaining with the current NSTimer before logout?
The view controller implementation file for the application looks like the following,
#import "ViewControllerCreate.h"
#import "math.h"
#interface ViewControllerHome ()
#define kMaxIdleTimeSeconds 20.0
#implementation ViewControllerHome
#end
- (void)viewDidLoad
{
// 5AUG13 - idle time logout
[self resetIdleTimer];
int idleTimerTime_int;
idleTimerTime_int = (int)roundf(kMaxIdleTimeSeconds);
_idleTimerTime.text = [NSString stringWithFormat:#"%d secs til",idleTimerTime_int];
}
- (void)viewDidUnload
{
[self setIdleTimerTime:nil];
// set the idleTimer to nil so the idleTimer doesn't tick away on the welcome screen.
idleTimer = nil;
[super viewDidUnload];
}
#pragma mark -
#pragma mark Handling idle timeout
- (void)resetIdleTimer {
if (!idleTimer ) {
idleTimer = [NSTimer scheduledTimerWithTimeInterval:kMaxIdleTimeSeconds
target:self
selector:#selector(idleTimerExceeded)
userInfo:nil
repeats:YES];
}
else {
if(fabs([idleTimer.fireDate timeIntervalSinceNow]) < kMaxIdleTimeSeconds-1.0) {
[idleTimer setFireDate:[NSDate dateWithTimeIntervalSinceNow:kMaxIdleTimeSeconds]];
}
}
}
- (void)idleTimerExceeded {
NSLog(#"lets see what happens");
[idleTimer invalidate];
[self logout:nil];
[self resetIdleTimer];
}
// method is fired when user touches screen.
- (UIResponder *)nextResponder {
[self resetIdleTimer];
return [super nextResponder];
}
#end
I wouldn't use the code you posted at all. Why not start the label with the max idle time, then call the timer's action method once every second, and subtract 1 from the label's text's intValue. When the label's value reaches 0, do what ever you need to do, and invalidate the timer.
Something like this:
- (void)viewDidLoad {
[super viewDidLoad];
self.label.text = #"1000";
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:#selector(countDown:) userInfo:nil repeats:YES];
}
-(void)countDown:(NSTimer *) aTimer {
self.label.text = [NSString stringWithFormat:#"%d",[self.label.text intValue] - 1];
if ([self.label.text isEqualToString:#"0"]) {
//do whatever
[aTimer invalidate];
}
}

Creating multiple timers that are self invalidating

I am trying to program an app for the Iphone using Xcode 4.3.1, and what I would like to be able to do is press a button and touch somewhere on the touchscreen and have a label(with a timer attached) show up and count down from some number. When the timer reaches 0:00, I want it to invalidate itself and to do this I need to keep it's reference.
I do not know how many total number of labels/timers I will use before-hand so I was thinking I would use an array to store each one. I have very little knowledge knowledge of the Objective-C language. Everything I have done so far has just been replicating examples I have seen in other stackoverflow questions, trying to understand them. I have been able to build a relatively functional timer so far.
Below is my current code for my timer. Currently it is just a pre-made button connected to a pre-made label with all the functionality that I want my timer to have. It starts at 5 minutes, formats itself to minutes:seconds, and invalidates the timer when it reaches 0:00. The button also acts as a stop/reset function once the timer has started.
ViewController.h
#interface ViewController : UIViewController{
IBOutlet UILabel *timerDisplay;
NSTimer *timer;
bool timerActive;
int MainInt;
int minutes;
int seconds;
}
#property (nonatomic, retain) UILabel *timerDisplay;
-(IBAction)start:(id)sender;
-(void)countdown;
-(void)timerStop;
-(void)timeFormat;
#end
ViewController.m
#implementation ViewController
#synthesize timerDisplay;
-(void)timeFormat{
seconds = MainInt % 60;
minutes = (MainInt - seconds) / 60;
timerDisplay.text = [NSString stringWithFormat:#"%d:%.2d", minutes, seconds];
}
-(void)countdown {
MainInt -= 1;
[self timeFormat];
if (MainInt <=0){
timerActive = NO;
[self->timer invalidate];
self->timer = nil;
}
}
-(IBAction)start:(id)sender {
MainInt = 300;
[self timeFormat];
if(timerActive == NO){
timerActive = YES;
self->timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(countdown) userInfo:nil repeats:YES];
}
else {
timerActive = NO;
[self->timer invalidate];
self->timer = nil;
}
}
Any help at all would be appreciated. I would mostly like help with being able to have multiple timers at one time using an array or something. Hardcoding a large amount of timers would be a silly thing to do.
Cheers.
EDIT 2:
I have the code below to act as my App, this is pretty much exactly what I want it to do. Except in this code, I can only have one timer running at a time, this is my problem.
In this code I store the value of the most recent tap on the touchscreen(to use its co-ordinates to place the timer somewhere on the screen), and a single button that when I press it, a running timer(with UILabel) will appear at the location of the previously stored tap. It will run until completed and then invalidate itself and remove itself from the view.
This works fine.
However when I press the button again before the original timer has completed, it will simply create a new timer(with UILabel) at the new location. This new timer will work fine, but the old one has lost its timer reference so it cannot finish, and I cannot remove it.
ViewController.h:
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController{
UILabel *timerDisplay;
NSTimer *timer;
CGPoint startPoint;
int MainInt;
}
#property CGPoint startPoint;
-(IBAction)startTimer:(id)sender;
-(void)countdown;
-(void)timeFormat;
-(void)start;
#end
ViewController.m:
#implementation ViewController
#synthesize startPoint;
-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *theTouch = [touches anyObject];
startPoint = [theTouch locationInView:self.view];
}
-(IBAction)startTimer:(id)sender {
timerDisplay = [[UILabel alloc] initWithFrame:CGRectMake(startPoint.x -15, startPoint.y - 15, 50, 50)];
timerDisplay.textAlignment = UITextAlignmentCenter;
timerDisplay.text = [NSString stringWithFormat:#"%i", MainInt];
timerDisplay.backgroundColor = [UIColor greenColor];
timerDisplay.textColor = [UIColor whiteColor];
[self.view addSubview:timerDisplay];
[self start];
}
-(void)timeFormat{
int seconds = MainInt % 60;
int minutes = (MainInt - seconds) / 60;
timerDisplay.text = [NSString stringWithFormat:#"%d:%.2d", minutes, seconds];
}
-(void)countdown {
MainInt -= 1;
[self timeFormat];
if (MainInt <= 0){
[self->timer invalidate];
self->timer = nil;
[timerDisplay removeFromSuperview];
}
}
-(void)start {
MainInt = 5;
[self timeFormat];
if(self->timer == nil){
self->timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:#selector(countdown) userInfo:nil repeats:YES];
}
}
#end
I was hoping someone could help me in creating a new class to hold each of the new timer instances and keep the references to them. I lack the knowledge of Objective C to get this done. Or perhaps you could link me to an example that could help me.
Cheers.
Your code looks OK to me. I would say that you have redundant instance variables. timerActive is redundant because you can just check if self->timer is non-nil. seconds and minutes could just be local to -timeFormat, they don't need to be instance variables.
Is the issue that you don't know how to generalize this to multiple buttons-label pairs with multiple timers? I'd suggest that you create a new class to act as a controller for each button-label pair. The class would derive from NSObject. What are currently instance variables of your view controller class would instead be instance variables of this new class, although you wouldn't necessarily use IBOutlet for the label. (An outlet is connected in a NIB, but these would presumably be created dynamically and would be connected in code.)
You'd allocate and initialize an instance of this new class for each button-label pair you want. You'd pass in the pointer to the label and the starting time value. You might also pass in the pointer to the ViewController object which owns it, so that it can inform it when it has stopped or something like that. The corresponding button would be set to target this new controller. ViewController would keep track of each of these controllers in a mutable array. When it is done with one, it would remove its label, its button, and the controller.
Does that help?

UIButton Touch and Hold

I haven't found a very easy way to do this. The ways I've seen require all these timers and stuff. Is there any easy way I can hold a UIButton and cause it to repeat the action over and over until it gets released?
You can do the following: Make an NSTimer that will start up when the app starts or in viewDidLoad and also make a boolean.
For example:
//Declare the timer, boolean and the needed IBActions in interface.
#interface className {
NSTimer * timer;
bool g;
}
-(IBAction)theTouchDown(id)sender;
-(IBAction)theTouchUpInside(id)sender;
-(IBAction)theTouchUpOutside(id)sender;
//Give the timer properties.
#property (nonatomic, retain) NSTimer * timer;
Now in your implementation file (.m):
//Synthesize the timer
#synthesize timer;
//When your view loads initialize the timer and boolean.
-(void)viewDidLoad {
g = false;
timer = [NSTimer scheduledTimerWithInterval: 1.0 target:self selector:#selector(targetMethod:) userInfo:nil repeats: YES];
}
Now make an IBAction for "Touch Down" set the boolean to lets say true. Then make another IBAction button for "Touch Up Inside" and "Touch Up Outside" assign the boolean to false.
For example:
-(IBAction)theTouchDown {
g = true;
}
-(IBAction)theTouchUpInside {
g = false;
}
-(IBAction)theTouchUpOutside {
g = false;
}
Then in that NSTimer method, put the following:(assume g is the boolean you have declared)
-(void) targetmethod:(id)sender {
if (g == true) {
//This is for "Touch and Hold"
}
else {
//This is for the person is off the button.
}
}
I hope this simplifies everything... I know it still uses a timer but there is not another way.
Unfortunately, it still looks like you have to code this functionality for yourself. simplest way (You still need a timer though):
A function that performs the action you want to repeat:
-(void) actionToRepeat:(NSTimer *)timer
{
NSLog(#"Action triggered");
}
in your .h file declare and set a property for a timer:
#interface ClassFoo
{
NSTimer* holdTimer;
}
Then in the .m make two IBActions:
-(IBAction) startAction: (id)sender
{
holdTimer = [NSTimer scheduledTimerWithTimeInterval:0.4 target:self selector:#selector(actionToRepeat:) userInfo:nil repeats:YES];
[holdTimer retain];
}
-(IBAction) stopAction: (id)sender
{
[holdTimer invalidate];
[holdTimer release];
holdTimer = nil;
}
Then Just link to the Touch Down event in IB from the button to startAction and the Touch Up Inside to the 'Stop Action'. It isn't a one liner but it allows you to customise the rate the action repeats as well as allowing you to trigger it from another outlet/action.
You might consider subclassing UIButton and adding this functionality if you are going to be using this functionality often - then it is only (slightly) painful to implement the first time.
An other way to use this NBTouchAndHoldButton. This is exactly what you want, and very easy to implement it:
TouchAndHoldButton * pageDownButton = [TouchAndHoldButton buttonWithType:UIButtonTypeCustom];
[pageDownButton addTarget:self action:#selector(pageDownAction:) forTouchAndHoldControlEventWithTimeInterval:0.2];
Good luck!
I cannot reply to the first one, but this line:
timer = [NSTimer scheduledTimerWithInterval: 1.0 target:self selector:#selector(targetMethod:) userInfo:nil repeats: YES];
for at least iOS 4.1 and newer needs to be:
timer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target:self selector:#selector(targetMethod:) userInfo:nil repeats: YES];
I know this is an old question, but as an easy way, like to consider using "[NSObject performSelector:withObject:afterDelay:]" to repeatedly invoke methods in any particular time interval.
In this case:
NSTimeInterval someTimeInterval = 1;
- (IBAction)action:(id)sender {
UIButton * const button = sender;
if (button.state != UIControlStateHighlighted) {
return;
}
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:_cmd object:sender];
[self performSelector:_cmd withObject:sender afterDelay:someTimeInterval];
}