© 2013 All rights reserved.
10

iOS Running a timer within your app is in the background

Sometimes, you need to run the timer when the application is in the background as you do this?

Simple solution is to use a function applicationDidEnterBackground, which can we found in AppDelegate.

This function starts automatically if you go by in the background.

In this function we can create UIBackgroundTaskIdentifier, which run task after time:

In this case the function (methodRunAfterBackground) starts 10 seconds after you switch applications in the background

Comments (10)

I cant wait to go through additional from you. That is really an incredible weblog.

Viruss

In NSTimer i set 6o and repeat =yes ,But this will be work for only 10 minutes, after 10 min. timer is stopped,
as there any other solution for run app in background,

admin

Look at this post: http://zaachi.com/2013/09/30/ios-locationmanager-location-update-in-my-own-interval-with-application-in-the-background.html
This is a solution where the task can run in the background for a long time

Applications must be set up to support the actions that run in the background. You can combine location update in interval and your method.

admin

iOS does not support to run the method in background in loop pernamently. You must combine it with allowed services.

IOS Developer

i used same method but after some time it will force to app shutdown and timer will stop

IOS Developer

it give me “has active assertions beyond permitted time” error and force to shutdown app.

plz note repeat mode = yes

Vinod

Very nice tutorial its help me lots.

uttam

Hi I used the below code for making calls and sending messages but the thing is when i run on device in background messages are not going again when I open the app from back ground it working agian

__block UIBackgroundTaskIdentifier bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
NSTimer* t = [NSTimer scheduledTimerWithTimeInterval:time target:self selector:@selector(startTrackingBg) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:t forMode:NSDefaultRunLoopMode];
[[NSRunLoop currentRunLoop] run];
});

Ullash

Thanks a lot, was searching for this. Subscribing you

Hussain

Thanks. It was really a helpful tutorial.

Leave a Reply to admin Cancel Reply

About
Hi, i am programmer from the Czech Republic. I love web development (Ruby, Ruby on Rails, PHP, Nette) and iOS development (Objective-C, Cocoa).
To cooperate, here is my phone:
+420 608 836