calling a method after each 60 seconds in iPhone
Asked Answered
A

6

33

I have created an GKSession and as its object is created, it starts search for availability of devices, as

 - (void)session:(GKSession *)session peer:(NSString *)peerID didChangeState:(GKPeerConnectionState)state {

I want to call this method after each 60 seconds, what should I do?

Antiphonal answered 15/4, 2011 at 8:49 Comment(1)
possible duplicate of How can I create a count down Timer for cocos2d?Implicatory
C
93

Use NSTimer

NSTimer* myTimer = [NSTimer scheduledTimerWithTimeInterval: 60.0 target: self
                                   selector: @selector(callAfterSixtySecond:) userInfo: nil repeats: YES];

After each 60.0 second , iOS will call the below function

-(void) callAfterSixtySecond:(NSTimer*) t 
{
    NSLog(@"red");
}
Crossruff answered 15/4, 2011 at 9:10 Comment(2)
but this is delegate method, called whenever state changed, like from available to unavailabe,Antiphonal
@Jhaliya: Will it work everytime i.e. if I implement this NSTimer in app delegate, I want the method to be called irrespective of viewcontroller I am in & irrespective of the app state whether in foreground, background or killed.Sheepwalk
I
13

Once you set NSTimer to scheduleWithTimeInterval it calls it immediately. You can use

  [self performSelector:@selector(doSomething) withObject:nil afterDelay:60.0f];
Illyricum answered 13/5, 2014 at 14:58 Comment(0)
M
3

Use the following code:

 NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval: 60.0 target: self
                               selector: @selector(timerFired:) userInfo: nil repeats: YES];

 - (void)timerFired:(NSTimer*)theTimer{
 if(condition){
       [theTimer isValid]; //recall the NSTimer
       //implement your methods
  }else{
      [theTimer invalidate]; //stop the NSTimer
 }
}
Mohair answered 9/5, 2016 at 11:30 Comment(0)
C
2

Swift 3:

Timer.scheduledTimer(withTimeInterval: 60, repeats: true, block: { (timer) in 
print("That took a minute")
})
Corposant answered 14/7, 2017 at 22:24 Comment(0)
Z
0

You can use schedular method...

-(void) callFunction:(CCTime)dt 
{
    NSLog(@"Calling...");
}

you can call above function by using this...

[self schedule:@selector(callFunction:) interval:60.0f];
Zymogen answered 15/4, 2011 at 9:24 Comment(1)
Yeah..you can unschedule this method whenever you want.Zymogen
B
0

Swift 5.0

var timer = Timer.scheduledTimer(timeInterval: 60.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)

@objc func updateTimer() {
   print("1 min passed")
}
Boehmer answered 6/9, 2019 at 8:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.