保持NSTimer运行甚至应用程序在ios中的后台运行
问题描述:
即使我的应用程序在后台运行,我也想继续在后台执行特定的任务。保持NSTimer运行甚至应用程序在ios中的后台运行
这是我试过的代码。定时器仅在进入背景时触发一次。
- (void)applicationDidEnterBackground:(UIApplication *)application
{
NSTimer * timer = [NSTimer timerWithTimeInterval:2.0
target:self
selector:@selector(timerTicked)
userInfo:nil
repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer
forMode:NSDefaultRunLoopMode];
}
- (void) timerTicked
{
NSLog(@"Timer method");
}
答
- (void)applicationDidEnterBackground:(UIApplication *)application {
UIBackgroundTaskIdentifier bgTask = UIBackgroundTaskInvalid;
bgTask = [[UIApplication sharedApplication]
beginBackgroundTaskWithExpirationHandler:^{
[[UIApplication sharedApplication] endBackgroundTask:bgTask];
}];
// NotificationTimer its timer
// myMethod1 call ur method
NotificationTimer = [NSTimer scheduledTimerWithTimeInterval: Interval
target: self
selector:@selector(myMethod1)
userInfo: nil repeats:YES];
}
我认为它对你的帮助
+0
这应该用于告诉iOS,在进入睡眠模式之前,您需要完成一些事情。 Cf Apple doc'您不应该使用这种方法,只是为了让您的应用程序在移动到后台后继续运行。“# 最重要的是,这种方法在很长一段时间内不会工作。 – KIDdAe 2015-03-03 13:27:09
答
你不能在后台有一个计时器。它可能会工作很短的时间,但如果您没有注册后台模式,您的应用程序将很快进入睡眠模式。
可用的模式可能是:
- 音频
- 位置更新
- 背景取
- 其他...
嘿,这篇文章似乎是你的问题的解决方案。 http://stackoverflow.com/questions/12916633/how-to-run-the-timer-in-background-of-the-application – LoVo 2015-03-03 10:20:57
@LoVo你解决了我的问题。谢谢.. – Rakesh 2015-03-03 10:33:43
@Rakesh不,它不会。看看这种方法的应用程序文档。 https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIApplication_Class/#//apple_ref/occ/instm/UIApplication/beginBackgroundTaskWithExpirationHandler: 你在做什么是反对苹果推荐,这赢了即使工作超过几分钟 – KIDdAe 2015-03-03 13:29:04