0

In my iOS application I am using NSTimer to to record some events happening in my app. Now I want to keep them recording when my app goes to the background so that even if my app is in the background, my NSTimer will continue to record the events. Can somebody guide me how I can achieve this behaviour?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Madu
  • 4,849
  • 9
  • 44
  • 78

2 Answers2

0

Timers can not run in background. The only thing you can do is, record the time when application goes into background and when application comes into foreground. Take the difference and do the appropriate action.

Apurv
  • 17,116
  • 8
  • 51
  • 67
  • What kind of events are happening? What is the impact of those events on Timer? – Apurv Jul 10 '14 at 11:28
  • Actually i am communicating with some other device and that device send me acknowledgement and then i send again. if some thing went wrong then i have to start the whole process from the start instead of user to stuck on that view. – Madu Jul 10 '14 at 11:31
  • In that case , you may not require to have Timers. – Apurv Jul 10 '14 at 11:36
0

Unless you enable one of the Background modes, it is not gonna work.

Why?

You have around 10 minutes of background execution after this the timer is stopped by ios.

The timer will not fire after app is locked (iOS7), since ios suspends the foreground app and bgTask will not get fire again.

There is some workarounds, consider to check below

// NSTimer run when app in background

[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];
loop = [NSTimer scheduledTimerWithTimeInterval:0.25 target:self selector:@selector(Update) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:loop forMode:NSRunLoopCommonModes];

Anotherway check this NSTimer in Background

Community
  • 1
  • 1
falcon143
  • 702
  • 4
  • 19
  • This 10 mins background time is for every normal app ? for example the apps which are not playing Audio or the VOIP apps and the other categories mentioned by apple. do you mean that every app gets a 10 mins time when it goes to background. Can you please give apple documentation reference for that. – Madu Jul 10 '14 at 12:25
  • check this https://developer.apple.com/library/ios/documentation/iphone/conceptual/iphoneosprogrammingguide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html#//apple_ref/doc/uid/TP40007072-CH4-SW20 – falcon143 Jul 10 '14 at 12:38
  • and also https://developer.apple.com/library/ios/documentation/uikit/reference/UIApplication_Class/Reference/Reference.html – falcon143 Jul 10 '14 at 12:39