iOS后台保持程序不休眠,一般十分钟左右之内,只需要实现以下方法即可,可实现后台播放音乐,处理socket消息等,以下代码即可
@implementation AppDelegate
{
UIBackgroundTaskIdentifier _backIden;
}- (void)applicationDidEnterBackground:(UIApplication *)application {
self.needStop = YES;
[NoticeTools setneedConnect:NO];
if (self.hasMoveFloatView) {//缓存播放流助手位置
NoticeAssestPointModel *cachePointM = [NoticeAssestPointModel new];
cachePointM.firstGetin = YES;
cachePointM.inPointX = self.floatPoint.x;
cachePointM.inPointY = self.floatPoint.y;
cachePointM.floatViewIsOut = self.floatViewIsOut;
[NoticeComTools saveAssestPointModel:cachePointM];
}
[self beginTask];
}
/// app进入后台后保持运行
- (void)beginTask {
_backIden = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
//如果在系统规定时间3分钟内任务还没有完成,在时间到之前会调用到这个方法
[self endBack];
}];
}
/// 结束后台运行,让app挂起
- (void)endBack {
//切记endBackgroundTask要和beginBackgroundTaskWithExpirationHandler成对出现
[[UIApplication sharedApplication] endBackgroundTask:_backIden];
_backIden = UIBackgroundTaskInvalid;
}这样即可
在iOS中,通过实现特定的方法如`applicationDidEnterBackground:`和`beginTask`,可以保持程序在后台运行大约10分钟,以支持后台音乐播放和处理socket消息。使用`beginBackgroundTaskWithExpirationHandler`启动后台任务,并在必要时调用`endBack`来结束任务,确保遵循系统的后台执行规则。

8076

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



