我正在制作一个基准应用程序,仅用于测试目的。我不打算将其转到 App Store。
我需要的是我的 NSTimer 使用 UIBackgroundTaskIdentifier 继续在后台运行,将数据保存到核心数据数据库,最后将数据推送到服务器(我正在使用 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 方法简单地调用核心数据类并进行必要的插入。
我读过有关 VoIP 和音乐播放部分的内容,但不知道哪一个最适合我的情况,也不知道如何实现它们。
最佳答案
我自己弄明白了,对于其他有类似问题的人,我所做的是首先打开您的 Info.plist 文件上的位置更新标志。为此,您必须在 Xcode 4 上添加名为“Required Background Modes”的 Key,然后作为值,选择“App registers for location updates”
我的 .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 分钟后启动并立即停止定位服务。这足以让应用程序无限期地保持事件状态,除非您终止该进程。
关于objective-c - 如何让我的应用程序在后台运行 NSTimer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9220494/