Make Timer Run on Background iOS for More Than 3 Minutes

Count while in background (NSTimer for more than 3 mins)

You can do it by following way:

1) First include required background mode keys into your Info.plist

2) Check and add following line of code for adding background working of location manager in iOS 9 (update: also works in iOS 10):

if ([self.locationManager respondsToSelector:@selector(setAllowsBackgroundLocationUpdates:)]) {
[self.locationManager setAllowsBackgroundLocationUpdates:YES];
[self.locationManager pausesLocationUpdatesAutomatically:NO];
}

3)Then create a new timer with repeated continuously with every 1 sec.

4)In that timer method add these two line of code.

[self.locationManager stopUpdatingLocation];
[self.locationManager startUpdatingLocation];

This make your app run in background more than 3 mins. To be aware, the battery usage may be costly.

Swift - Best way to run timer in background for iphone apps

In a word, no. You can ask for background time, but recent versions of iOS give you 3 minutes.

If you are a background sound playing app or navigation app you are allowed to run in the background for longer, but you have to ask for those permissions and the app review board will check.

The bottom line is that third parties can't really do a timer app that counts down an arbitrary time longer than 3 minutes.

You might want to use timed local notifications. You can make those play a sound when they go off. Search in the Xcode docs on UILocalNotification.

Run timer in background

It's possible through a token that identifies a request to run in the background.

Like this: var bgTask = UIBackgroundTaskIdentifier()

Here is how to use it:

var bgTask = UIBackgroundTaskIdentifier()
bgTask = UIApplication.shared.beginBackgroundTask(expirationHandler: {
UIApplication.shared.endBackgroundTask(bgTask)
})
let timer = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(notificationReceived), userInfo: nil, repeats: true)
RunLoop.current.add(timer, forMode: RunLoopMode.defaultRunLoopMode)

I hope it would be useful!

Issues regarding to Timer running in the background iOS 10

No, you can run background tasks for up to 5 minutes, use the background update functionality to trigger app refresh, or use notifications to trigger background actions. There is no way in iOS to guarantee that any code will be run consistently in the background after 30 minutes. Local notifications will enable your code to run after the user selects an action in a notification. Silent push notifications can run some code in the background open receipt, but require an internet connection and are not guaranteed to be delivered.

See this question for more info:
iOS Timer in the background



Related Topics



Leave a reply



Submit