如何让我的应用程序在后台运行NSTimer?

时间:2012-02-09 23:20:37

标签: objective-c nstimer voip background-music

我正在为测试目的制作基准测试应用程序。我不打算去App Store。

我需要的是我的NSTimer使用UIBackgroundTaskIdentifier继续在后台运行,将数据保存到Core Data数据库并最终将数据推送到服务器(我正在使用Parse),当然在一定的时间间隔之后,当然

基本上,我还没有找到任何适用于我的具体案例的问题。我这样设置我的NSTimer:

    UIBackgroundTaskIdentifier bgTask;
UIApplication  *app = [UIApplication sharedApplication];
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
    [app endBackgroundTask:bgTask]; 
}];

self.timer = [NSTimer scheduledTimerWithTimeInterval:self.localInterval target:self selector:@selector(updateCoreData:) userInfo:nil repeats:YES];

方法updateCoreData只调用Core Data类并进行必要的插入。

我已经阅读过关于VoIP和音乐播放部分的内容,但不知道哪一个最适合我的情况,也不知道如何实现它们。

2 个答案:

答案 0 :(得分:37)

我自己想出来,对于其他遇到类似问题的人,我所做的就是首先打开Info.plist文件中的位置更新标志。要做到这一点,你必须添加名为"所需的背景模式"在Xcode 4上,然后选择" App注册位置更新"

我的.h文件中有一个如此声明的计时器:

NSTimer *silenceTimer;
@property (nonatomic, retain) NSTimer *silenceTimer;

然后在.m文件中,我声明它是这样的:

UIBackgroundTaskIdentifier bgTask;
UIApplication  *app = [UIApplication sharedApplication];
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
    [app endBackgroundTask:bgTask]; 
}];
self.silenceTimer = [NSTimer scheduledTimerWithTimeInterval:300 target:self
selector:@selector(startLocationServices) userInfo:nil repeats:YES];

最后,在选择器方法上,我做了以下内容:

-(void)startLocationServices {
    [locationManager startUpdatingLocation];
    [locationManager stopUpdatingLocation];
}

这将创建一个计时器,启动并在5分钟后立即停止位置服务。这将足以让应用程序无限期地保持活力,除非你杀死这个过程。

答案 1 :(得分:2)

XCode 6.3.1,适用于iOS 8.3

我在应用之间遇到了很大的差异。使用调试器和相同的应用程序插入运行XCode的Mac时的行为。不插电的行为。

在目前的iOS版本8.3中,最多分配的应用程序在后台运行180秒,以便使用到期处理程序进行有限长时间运行任务。

无论您尝试什么,在手机拔掉电源后,您的应用程序将在180秒或更早的时间内被系统杀死。我已经做了大量的测试和技巧来证实这一点。看我的帖子......

My NSTimer Post

这是一个简洁的方法,可以告诉您的应用在终止之前还剩多少时间,请注意,这次您无法保证。

NSTimeInterval backgroundTimeRemaining = [[UIApplication sharedApplication] backgroundTimeRemaining];

if (backgroundTimeRemaining == DBL_MAX)
{
    NSLog(@"background time remaining = undetermined");
}
else
{
    NSLog(@"background time remaining = %0.2f sec.", backgroundTimeRemaining);
}

希望这有助于您的调查。干杯!