How to automatic call function every x time [duplicate] - ios

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
How to call function in every “X” minute?
How to periodically call a certain function?
- (void)viewDidLoad
{
[super viewDidLoad];
[self checkAlert];
}
-(void)checkAlert{
// Server output Alert Note
NSString *alert_note_hostStr = #"http://www.loxleyintranet.com/MobileApplication/xml/alert_note.php";
NSData *alert_note_dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:alert_note_hostStr]];
NSString *alert_note_serverOutput = [[NSString alloc] initWithData:alert_note_dataURL encoding:NSASCIIStringEncoding];
if ([alert_note_serverOutput isEqualToString:#"0"]) {
alertImage.hidden = YES;
alertLabel.hidden = YES;
underMainBG.hidden = YES;
alertLabel.text = [NSString stringWithFormat:#"No Alert"];
}else{
alertLabel.text = [NSString stringWithFormat:#"You've Got Note (%#)" ,alert_note_serverOutput];
}
}
How can I call [self checkAlert]; every x minutes or seconds?

Use [NSTimer scheduledTimerWithTimeInterval:60.0 target:self
selector:#selector(checkAlert) userInfo:nil repeats:YES];.

[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:#selector(myTimerTick:) userInfo:nil repeats:YES]; // the interval is in seconds...
...then your myTimerTick: method should look like this..
-(void)myTimerTick:(NSTimer *)timer
{
if(some_contiditon)
{
// Do stuff...
}
else
{
[timer invalidate]; //to stop and invalidate the timer.
}
}

Related

make sound loop Alerts every five seconds

I'm trying to write a simple loop sound Alerts every five seconds
How can i add it please
tweak for cydia
Tweak.xm template
if (lowenabled) {
if ([batString isEqualToString:lowbatPercent_String]) {
if (lowplayer) {
return;
}
if (lowsound == 0)
soundFilePath = [NSString stringWithFormat:#"%#/Super Mario.mp3", bundlePrefix];
else if (lowsound == 1)
soundFilePath = [NSString stringWithFormat:#"%#/Super Mario 1.mp3", bundlePrefix];
soundFileURL = [NSURL fileURLWithPath:soundFilePath];
lowplayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
lowplayer.numberOfLoops = 3;
[lowplayer play];
} else {
if (lowplayer) {
lowplayer = nil;
}
}
}
}
%end
Include to fire timer:
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:#selector(playSound:) userInfo:nil repeats:YES];
[timer fire];
Put method in the same class:
- (void)playSound {
// the code you included here that plays the sound
}
Docs for NSTimer's fire method

Persistent allocation of Heap Memory NSTimer

I discovered an issue with my sample project. I simply create a scheduledTimer that "animate" a label and then, when I reached the result I want, I invalidate the timer and I set an another one, this time as a "clock".
This is the code I use
//
// ViewController.m
//
//
//
//
//
#import "ViewController.h"
#define ANIMATION_INTERVAL 0.07 // in secondi
#define ANIMATION_DURATION 1 // in secondi
#interface ViewController ()
{
int contatore;
NSString *hour;
NSString *minute;
NSString *second;
}
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
contatore = 0;
[self startTimeAnimation];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)startTimeAnimation
{
NSTimer * animationTimer = [NSTimer scheduledTimerWithTimeInterval:ANIMATION_INTERVAL target:self selector:#selector(timeout:) userInfo:nil repeats:YES];
}
-(void)timeout: (NSTimer *)timer
{
// Simulate of the Timer Duration with a counter
if (contatore < ceilf(ANIMATION_DURATION/ANIMATION_INTERVAL))
{
// Proceed with animation
contatore++;
int tempHour = arc4random_uniform(24);
int tempMinute = arc4random_uniform(60);
int tempSecond = arc4random_uniform(60);
if (tempHour < 10)
{
hour = [NSString stringWithFormat:#"0%d", tempHour];
}
else
{
hour = [NSString stringWithFormat:#"%d", tempHour];
}
if (tempMinute < 10)
{
minute = [NSString stringWithFormat:#"0%d", tempMinute];
}
else
{
minute = [NSString stringWithFormat:#"%d", tempMinute];
}
if (tempSecond < 10)
{
second = [NSString stringWithFormat:#"0%d", tempSecond];
}
else
{
second = [NSString stringWithFormat:#"%d", tempSecond];
}
_orarioLbl.text = [NSString stringWithFormat:#"%#:%#:%#", hour, minute, second];
}
else
{
// Stops animation
[timer invalidate];
[timer release];
contatore = 0;
[self setActualTime];
// Starts clock
NSTimer *clockTimer = [NSTimer timerWithTimeInterval:.5f target:self selector:#selector(updateClock) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:clockTimer forMode:NSRunLoopCommonModes];
}
}
-(void)updateClock
{
[self setActualTime];
}
-(void)setActualTime
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"HH"];
hour = [dateFormatter stringFromDate:[NSDate date]];
[dateFormatter setDateFormat:#"mm"];
minute = [dateFormatter stringFromDate:[NSDate date]];
[dateFormatter setDateFormat:#"ss"];
second = [dateFormatter stringFromDate:[NSDate date]];
_orarioLbl.text = [NSString stringWithFormat:#"%#:%#:%#", hour, minute, second];
[dateFormatter release];
}
#end
Since I start the "clock", memory still stays on 19/20 MB with constant persistent allocation. When the timer updates the minute value, persistent allocations increase as you can see in the gif! How is it possible? However, also 19MB of memory is too much for a simple clock, isn't it?
Profiling on Instruments, the new allocations are all about CoreGraphics!
EDIT I tested it on another device and the persistent allocations decreased. I don't know why, but I solved in this way. Thanks
NSTimer retains its target and that may lead to a retain cycle. Grab a weak reference to self and set that as the target:
__weak typeof(self) weakSelf = self;
NSTimer * animationTimer = [NSTimer scheduledTimerWithTimeInterval:ANIMATION_INTERVAL target:weakSelf selector:#selector(timeout:) userInfo:nil repeats:YES];
and
__weak typeof(self) weakSelf = self;
NSTimer *clockTimer = [NSTimer timerWithTimeInterval:.5f target:weakSelf selector:#selector(updateClock) userInfo:nil repeats:YES];
May I also recommend you create a property for the dateFormatter, as NSDateFormatters are expensive to create. And why are you releasing the dateFormatter? Are you not using ARC?

NSTimer Countdown issue

Hello I recently added a timer in my app so when the user clicks the balloon it starts the timer but I also have a tap counter hooked to the button as well. So heres my issue when I press the balloon multiple times the tap counter works and so does the timer but when start to tap faster the timer becomes stuck in a loop and when I stop tapping it, it counts down past zero into negatives really fast
How do I fix this?
- (IBAction)yourbuttonClicked1:(UIButton *)sender
{
//start a background sound
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:#"tap" ofType:
#"wav"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:soundFilePath ];
myAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil ];
[myAudioPlayer play];
//for Switch view
ViewController2 *nextView = [[ViewController2 alloc] initWithNibName:#"ViewController"
bundle: nil];
[self.navigationController pushViewController:nextView animated:YES];
This is where the timer code is I think it might be conflicting with the tap counter?
myTime = 60;
countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self
selector:#selector(countDown) userInfo:nil repeats:YES];
}
-(void)countDown {
myTime = myTime;
countdownLabel.text = [NSString stringWithFormat:#"%i", myTime];
if (myTime == 0) {
[countdownTimer invalidate];
}
}
This is where the timer code ends!
- (void) saveNumberOfTaps:(int)numberOfTaps {
[[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithInt:numberOfTaps]
forKey:#"numberOfTaps"];
NSLog(#"Saved numberOfTaps: %i", numberOfTaps);
}
- (int) getNumberOfTaps {
if ([[[NSUserDefaults standardUserDefaults] objectForKey:#"numberOfTaps"] intValue]) {
int numberOfTaps = [[[NSUserDefaults standardUserDefaults]
objectForKey:#"numberOfTaps"] intValue];
NSLog(#"Getting numberOfTaps: %i", numberOfTaps);
return numberOfTaps;
}
else {
NSLog(#"No taps saved yet");
return 0;
}
}
Try to modify your timer initialization in such way:
myTime = 60;
[countdownTimer invalidate];
countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self
selector:#selector(countDown) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:countdownTimer forMode:NSRunLoopCommonModes];
Check your -countDown method:
myTime = myTime;
Is it typo?

iOS Label Text Based On Timed Function

I've been trying to create a script that sets a timer and reduces a value by 33 each time it runs. In theory the timer should stop itself after 6 runs, but it keeps going and reaches negative values. Is there a reason for this?
-(void)checkValue:(NSTimer *)myTimer{
if(pplint > 0){
pplint = pplint-33;
NSString *ppllefttext = [NSString stringWithFormat:#"%d", pplint];
peopleleft.text = ppllefttext;
NSLog(#"Reduced Timer");
}
if(pplint < 0){
NSLog(#"Stop Timer");
[myTimer invalidate];
}
}
- (IBAction)gotocongrats{
pplint = 198;
NSString *ppllefttext = [NSString stringWithFormat:#"%d", pplint];
peopleleft.text = ppllefttext;
NSTimer * myTimer = [NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:#selector(checkValue:)
userInfo:nil
repeats:YES];
NSLog(#"Started Timer");
}
I took you code and edited it a bit and it works just fine for me.
-(void)checkValue:(NSTimer *)myTimer{
if(pplint > 0){
pplint = pplint-33;
NSLog(#"%i",pplint);
NSLog(#"Reduced Timer");
}
if(pplint <= 0){
NSLog(#"Stop Timer");
[myTimer invalidate];
}
}
- (IBAction)gotocongrats{
pplint = 198;
NSTimer * myTimer = [NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:#selector(checkValue:)
userInfo:nil
repeats:YES];
NSLog(#"Started Timer");
}

iOS NSTimer firing twice

Hi I'm trying to use NSTimer to create a countdown which and view this using a label. the problem is the label goes down in two's and i don't know why. any ideas?
heres my code
- (void)viewDidLoad
{
NSLog(#"%#", self.chosenTime);
[self startGame];
[super viewDidLoad];
NSString *timeString = self.chosenTime;
self.timer = [timeString intValue];
self.countdown.text = timeString;
// Do any additional setup after loading the view.
}
- (void)startGame
{
[self introCountdown];
[self performSelector:#selector(goAnimation) withObject:nil afterDelay:3.0];
NSString *timeString = self.chosenTime;
self.timer = [timeString intValue];
[self performSelector:#selector(startCountdown) withObject:nil afterDelay:4.0];
}
- (void)startCountdown
{
//self.countdownTimer = [NSTimer timerWithTimeInterval:1 target:self selector:#selector(decrementTimer:) userInfo:nil repeats:YES];
self.countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1.00 target:self selector:#selector(decrementTimer:) userInfo:nil repeats:YES];
}
- (void)decrementTimer:(NSTimer *)timer
{
if(self.timer > 0)
{
self.timer = self.timer - 1;
self.countdown.text = [NSString stringWithFormat:#"%d", self.timer];
}
else
{
[self.countdownTimer invalidate];
self.countdownTimer = nil;
}
}
This code seems to be correct. May be you are changing label's text from somewhere else?
Sorry for the misinterpretation, the code is correct, it seems a UI problem or handling label from somewhere else, attach your source with xib's if possible

Resources