I want in my iOS application to start a timer when the app is running in the background and when the app is closed. The timer must check every 30 minutes of there a new noti
add this code to in appdeleage.swift
var backgroundUpdateTask: UIBackgroundTaskIdentifier = 0
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
return true
}
func applicationWillResignActive(application: UIApplication) {
self.backgroundUpdateTask = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler({
self.endBackgroundUpdateTask()
})
}
func endBackgroundUpdateTask() {
UIApplication.sharedApplication().endBackgroundTask(self.backgroundUpdateTask)
self.backgroundUpdateTask = UIBackgroundTaskInvalid
}
func applicationWillEnterForeground(application: UIApplication) {
self.endBackgroundUpdateTask()
}
It is impossible to do something when the application is not in the foreground, with 100% certainty. You can use background fetch to be woken up periodically, but you can not control when it happens.
While there are some technical workarounds, and potentially even some hacky solutions (playing silent audio in the background), it sounds to me like your problem can be solved without the use of timers and background fetch.
Simply implement remote notifications. When your iOS receives a notification for your app, it will wake the app up and let it process for a while. You can then control what notifications are shown to the user, and maybe load some data in the background.
In broad terms, you need to:
AFAIK there is no way to run NSTimer after 180s in the background (in the production).
edit: If you enable Background modes you can get max 10 minutes. You can learn more eg. here.
Write this both methos in your Appdelegate.m file
//For Objective c
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[self TimerMethod];
}
-(void)TimerMethod
{
//Every 30 minute call the functions
_timer=[NSTimer scheduledTimerWithTimeInterval:1800.0f target:self selector:@selector(updateMethod:) userInfo:nil repeats:YES];
}
- (void)updateMethod:(NSTimer *)theTimer
{
NSLog(@"Timer set now");
}
//For Swift
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool
{
self.TimerMethod()
}
func TimerMethod()
{
var timer = NSTimer.scheduledTimerWithTimeInterval(1800, target: self, selector: "updateMethod", userInfo: nil, repeats: true)
}
func updateMethod()
{
print("set timer now")
}