iOS 保持app在后台不被kill
由于iOS在高版本之后很多保持后台的代码失效之后
在特殊情况下又要保持app长时间持有的问题,就可以用到后台音乐播放,但是这种容易被拒,所以最好是企业开发模式下使用
1、在xcode中开启后台模式
2、插入代码(找一个最小的音频文件拖入项目中)
//后台播放音乐
- (void)playbackgroud
{
_session = [AVAudioSession sharedInstance];
/*打开应用不影响别的播放器音乐*/
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:nil];
[_session setActive:YES error:nil];
//设置代理 可以处理电话打进时中断音乐播放
NSString *musicPath = [[NSBundle mainBundle] pathForResource:@"little moa - Tightrope" ofType:@"mp3"];
NSURL *URLPath = [[NSURL alloc] initFileURLWithPath:musicPath];
_player = [[AVAudioPlayer alloc] initWithContentsOfURL:URLPath error:nil];
[_player prepareToPlay];
_player.volume=0.0;
_player.numberOfLoops = -1;
[_player play];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioSessionInterruptionNotification:) name:AVAudioSessionInterruptionNotification object:nil];
}
// 监听中断通知调用的方法
- (void)audioSessionInterruptionNotification:(NSNotification *)notification{
/*
监听到的中断事件通知,AVAudioSessionInterruptionOptionKey
typedef NS_ENUM(NSUInteger, AVAudioSessionInterruptionType)
{
AVAudioSessionInterruptionTypeBegan = 1, 中断开始
AVAudioSessionInterruptionTypeEnded = 0, 中断结束
}
*/
int type = [notification.userInfo[AVAudioSessionInterruptionOptionKey] intValue];
switch (type) {
case AVAudioSessionInterruptionTypeBegan: // 被打断
[_player pause]; // 暂停播放
break;
case AVAudioSessionInterruptionTypeEnded: // 中断结束
[_player play]; // 继续播放
break;
default:
break;
}
}