防止iOS端关闭后台直播源码,实现后台保活
iOS13以后的直播源码进入后台后,由于系统控制内存会把进入后台的直播源码 kill掉来供其他应用使用,所以我们这里介绍一种保活的方式,利用循环播放无声的应约方式,防止iOS杀掉直播源码后台进程。
一、授权
打开后台声音权限
二、创建播放器
写一个单例并创建一个播放器,播放的是一个无声的mp3
+(instancetype)sharedKeepInstance{ static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _keepInstance = [[super allocWithZone:NULL]init]; }); return _keepInstance; } + (instancetype)allocWithZone:(struct _NSZone *)zone{ return [self sharedKeepInstance]; } - (void)initPlayer { [self.player prepareToPlay]; } - (AVAudioPlayer *)player { if (!_player) { NSError *error = nil; NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"mute-mp3" withExtension:@"mp3"]; AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:&error]; audioPlayer.numberOfLoops = NSUIntegerMax; _player = audioPlayer; NSLog(@"%s 初始化==:%@",__FUNCTION__,error); } return _player; }
三、启动监听
当直播源码启动时在- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 方法里面调用启动程序的监听:
//生命周期监听 [[RKKeepAlive sharedKeepInstance] startAppLifeCycleMonitor];
1、监听当程序进入后台时:
#pragma mark - App进入后台
- (void)applicationDidEnterBackground:(UIApplication *)application { if (self.lifeCycleEvent) { self.lifeCycleEvent(APPLifeCycle_EnterBackground); } } #pragma mark - App将要从后台返回 - (void)applicationWillEnterForeground:(UIApplication *)application { if (self.lifeCycleEvent) { self.lifeCycleEvent(APPLifeCycle_EnterForeground); } } #pragma mark – 当程序被杀进程时 - (void)applicationWillTerminate:(UIApplication *)application{ if (self.lifeCycleEvent) { self.lifeCycleEvent(APPLifeCycle_WillTerminate); } }
2、当程序进入后台时开始播放音乐、当进入前台时暂停
-(void)appDelegateBlockEvent:(YBAppLifeCycle)lifeCycleType { switch (lifeCycleType) { case APPLifeCycle_EnterForeground:{ //[self appActive]; //前台 NSLog(@"%s:应用将进入前台WillEnterForeground", __FUNCTION__); if (self.needKeepAliveInBackground) { [self.player pause]; } [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskIdentifier]; }break; case APPLifeCycle_EnterBackground:{ //[self backGround]; //后台 self.backgroundTaskIdentifier = [[UIApplication sharedApplication] beginBackgroundTaskWithName:kBgTaskName expirationHandler:^{ if (self.needKeepAliveInBackground) { [self.player play]; } if (self.backgroundTaskIdentifier != UIBackgroundTaskInvalid) { [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskIdentifier]; self.backgroundTaskIdentifier = UIBackgroundTaskInvalid; } }]; NSLog(@"%s:应用进入后台DidEnterBackground", __FUNCTION__); }break; case APPLifeCycle_WillTerminate:{ //杀进程 NSLog(@"%s:应用终止:WillTerminate", __FUNCTION__); }break; default: break; } }
这样就可以做到后台保活了,后续我们会继续分享直播源码开发的相关知识,感兴趣的话可以持续关注我们。
声明:以上内容为云豹科技原创,未经作者本人同意,禁止转载,否则将追究相关法律责任www.yunbaokj.com