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

Lil*_*arf 12 voip objective-c background-music nstimer

我正在为测试目的制作基准测试应用程序.我不打算去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];
Run Code Online (Sandbox Code Playgroud)

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

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

Lil*_*arf 37

我自己想出来,对于有类似问题的其他人,我做的是先打开Info.plist文件上的位置更新标志.为此,您必须在Xcode 4上添加名为"Required Background Modes"的密钥,然后作为值,选择"App registers for location updates"

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

NSTimer *silenceTimer;
@property (nonatomic, retain) NSTimer *silenceTimer;
Run Code Online (Sandbox Code Playgroud)

然后在.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];
Run Code Online (Sandbox Code Playgroud)

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

-(void)startLocationServices {
    [locationManager startUpdatingLocation];
    [locationManager stopUpdatingLocation];
}
Run Code Online (Sandbox Code Playgroud)

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