首先是最终部分代码。
- (void)applicationDidBecomeActive:(UIApplication *)application
{
[_timer setFireDate:[NSDate distantFuture]];
DLog(@"后台运行计数计时为%d",_count);
if(_count>180){
// [Context sharedInstance].isLogin=NO; // 后台运行超过三分钟,自动登出。 //暂时注掉,这个ZXJ告知现在由服务器控制,10分钟以后自动登出
}
}
然后是控制Count部分的代码
-(void)startListen:(NSTimer *)timer{
_count++;
DLog(@"count %d",_count);
}
最后是启动count部分的代码
NSError *setCategoryErr = nil;
NSError *activationErr = nil;
[[AVAudioSession sharedInstance]
setCategory: AVAudioSessionCategoryPlayback
error: &setCategoryErr];
[[AVAudioSession sharedInstance]
setActive: YES
error: &activationErr];
_timer=[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(startListen:) userInfo:nil
repeats:YES];
DLog(@"计时器初始化");
[_timer setFireDate:[NSDate distantFuture]];//关闭定时器
[self.window makeKeyAndVisible];
本文介绍了一个iOS应用如何实现后台运行计时功能,并在后台运行超过指定时间后自动登出用户。该方案利用了NSTimer来计数,并通过监听应用活跃状态调整计时器的行为。
1万+

被折叠的 条评论
为什么被折叠?



