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?

Jhaliya - Praveen Sharma
  • 31,697
  • 9
  • 72
  • 76
Chatar Veer Suthar
  • 15,541
  • 26
  • 90
  • 154
  • possible duplicate of [How can I create a count down Timer for cocos2d?](http://stackoverflow.com/questions/446717/how-can-i-create-a-count-down-timer-for-cocos2d) – mmmmmm Apr 01 '13 at 11:33

6 Answers6

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");
}
Jhaliya - Praveen Sharma
  • 31,697
  • 9
  • 72
  • 76
  • but this is delegate method, called whenever state changed, like from available to unavailabe, – Chatar Veer Suthar Apr 15 '11 at 09:31
  • 1
    @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. – iYoung Jun 03 '15 at 11:15
13

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

  [self performSelector:@selector(doSomething) withObject:nil afterDelay:60.0f];
Gal Marom
  • 8,499
  • 1
  • 17
  • 19
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
 }
}
Mannam Brahmam
  • 2,225
  • 2
  • 24
  • 36
2

Swift 3:

Timer.scheduledTimer(withTimeInterval: 60, repeats: true, block: { (timer) in 
print("That took a minute")
})
J. Doe
  • 12,159
  • 9
  • 60
  • 114
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];
Anish
  • 2,889
  • 1
  • 20
  • 45
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")
}
Gurjinder Singh
  • 9,221
  • 1
  • 66
  • 58