0

I have done research how to maintain the timer running when home button is pressed. But i am quite confused.

This is my code, how can i fix it and the timer continue running in background? Thanks in advance.

-(id)init {

if (self = [super init]) {
    self.timer = [[NSTimer alloc] init];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(startTimer) userInfo:nil repeats:YES];
}
return self;
}

+(Timer *)sharedSingleton {

static Timer *sharedSingleton = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
    sharedSingleton = [[Timer alloc] init];
});
return sharedSingleton;
}

-(void)startTimer {


i++;
_count = [NSNumber numberWithInteger:i];
[[NSNotificationCenter defaultCenter] postNotificationName:COUNT object:_count];
}
Nan
  • 496
  • 3
  • 21
  • do you want anything to happen when the timer finishes if the app is in the background? or do you want the timer to continue as before (minus whatever time it was in the background) if the app is brought to the front again? – Michael Dautermann Nov 08 '16 at 03:08
  • I want the timer continue timing when app is in background. Thanks in advace. – Nan Nov 08 '16 at 03:10
  • Why do you need the timer to run in the background? Your app won't be running. – rmaddy Nov 08 '16 at 03:13
  • Coz this is a sport app, for example, users receive a phone call and the app will be suspended. But i still want to let it keep counting. – Nan Nov 08 '16 at 03:14
  • 3
    When your app goes to the background, save the time. When it resumes in the foreground, get the current time. Subtract the saved background time from the current time and you'll know how long your timer has been running. – par Nov 08 '16 at 03:16
  • Possiblly a good idea – Nan Nov 08 '16 at 03:18
  • 1
    Not "*possibly* a good idea". That is the proper solution. Your app could be killed while in the background. You need to deal with the app being killed and restarted when the user tries to go back to it. – rmaddy Nov 08 '16 at 03:26
  • @rmaddy I agree, I just check the apple's doc, app will be kill in 10 minutes if u put on the stack – Nan Nov 08 '16 at 03:27
  • beginBackgroundTaskWithExpirationHandler method can handle this. I think so – Narendra Pandey Nov 08 '16 at 04:43
  • @NarendraPandey No, that only gives you about 30 seconds. – rmaddy Nov 08 '16 at 04:53
  • Actually when application is in background uptill that method can be run. if suspend your application then it will stopped. @rmaddy – Narendra Pandey Nov 08 '16 at 05:10
  • A handler to be called shortly before the app’s remaining background time reaches 0. You should use this handler to clean up and mark the end of the background task. Failure to end the task explicitly will result in the termination of the app. The handler is called synchronously on the main thread, blocking the app’s suspension momentarily while the app is notified. – Narendra Pandey Nov 08 '16 at 05:12

0 Answers0