我正在开发一个企业应用程序,它必须定时报告信息,特别是当应用程序在后台时。
- (void)applicationWillResignActive:(UIApplication *)application {
//stuff
UIApplication *app = [UIApplication sharedApplication];
//create new uiBackgroundTask
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
//and create new timer with async call:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//run function methodRunAfterBackground
timerOne = [NSTimer scheduledTimerWithTimeInterval:100 target:self selector:@selector(refreshInactiveTimer) userInfo:nil repeats:YES];
timerTwo = [NSTimer scheduledTimerWithTimeInterval:300 target:self selector:@selector(postActivity) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timerOne forMode:NSDefaultRunLoopMode];
[[NSRunLoop currentRunLoop] addTimer:timerTwo forMode:NSDefaultRunLoopMode];
[[NSRunLoop currentRunLoop] run];
});
}
- (void)applicationWillEnterForeground:(UIApplication *)applicationq {
[[UIApplication sharedApplication] endBackgroundTask:bgTask];
[timerOne invalidate];
[timerTwo invalidate];
}
-(void)refreshInactiveTimer { //this function plays a short inaudible sound which refreshes the background timer
AVSpeechSynthesizer *synth = [[AVSpeechSynthesizer alloc] init];
AVSpeechUtterance *utter = [[AVSpeechUtterance alloc] initWithString:@"up"];
[utter setVolume:0.0];
[synth speakUtterance:utter];
}
-(void)postActivity {
//this function makes a NSURLRequest that posts small data back to server side
}
代码按预期工作,但问题是它占用了100%的CPU(根据分析器)。我注意到,当我在拔下电源插头时进行测试时,电池似乎也很快耗尽,所以CPU肯定会消失。也许我在这里错过了一些小事。
注意:是的我知道这是不好的做法,Apple会拒绝使用这种方法的应用程序。但是,正如我所提到的,这是一个永远不会在App Store中存在且永远不会分发给普通公众的企业应用程序。