iOS:APP后台永久保活方法
Signing&Capabilites开启Audio,AirPlay,and Picture in Picture模式
应用在后台时播放声音信息,可以利用此模式播放无声音频,APP进入后台播放无声音频,可以实现APP长时间保活
代码如下
编写音乐播放类
#import <Foundation/Foundation.h>
#import<AVFoundation/AVFoundation.h>
@interface BackgroundPlayer : NSObject<AVAudioPlayerDelegate>
@property(nonatomic,strong)AVAudioPlayer* player;
- (void)startPlayer;
- (void)stopPlayer;
@end
#import "BackgroundPlayer.h"
@implementation BackgroundPlayer
- (void)startPlayer
{
if(_player&& [_playerisPlaying]) {
return;
}
AVAudioSession *session = [AVAudioSession sharedInstance];
[[AVAudioSession sharedInstance] setMode:AVAudioSessionModeDefault error:nil];
NSString* route = [[[[[AVAudioSession sharedInstance] currentRoute] outputs] objectAtIndex:0] portType];
if ([route isEqualToString:AVAudioSessionPortHeadphones] || [route isEqualToString:AVAudioSessionPortBluetoothA2DP] || [route isEqualToString:AVAudioSessionPortBluetoothLE] || [route isEqualToString:AVAudioSessionPortBluetoothHFP]) {
if(@available(iOS10.0, *)) {
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord
withOptions:(AVAudioSessionCategoryOptionMixWithOthers | AVAudioSessionCategoryOptionAllowBluetooth | AVAudioSessionCategoryOptionAllowBluetoothA2DP)
error:nil];
}else{
// Fallback on earlier versions
}
}else{
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord
withOptions:(AVAudioSessionCategoryOptionMixWithOthers | AVAudioSessionCategoryOptionDefaultToSpeaker)
error:nil];
}
[session setActive:YESerror:nil];
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"payment" ofType:@"mp3"];
NSURL*fileURL = [[NSURLalloc]initFileURLWithPath:filePath];
if(!fileURL) {
NSLog(@"找不到播放文件");
}
_player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
[_player prepareToPlay];
[_player setDelegate:self];
_player.volume=0.0;
_player.numberOfLoops = -1;
BOOLret = [_playerplay];
if(!ret) {
NSLog(@"播放失败play failed,please turn on audio background mode");
}
}
- (void)stopPlayer
{
if(_player) {
[_playerstop];
_player=nil;
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setActive:NOerror:nil];
NSLog(@"播放暂停stop in play background success");
}
}
@end
在AppDelegate.m中添加监听
UIApplicationWillEnterForegroundNotification(应用进入前台通知)UIApplicationDidEnterBackgroundNotification(应用进入后台通知)
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillEnterForeground) name:UIApplicationWillEnterForegroundNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appDidEnterBackground) name:UIApplicationDidEnterBackgroundNotification object:nil];
@property(nonatomic,strong)BackgroundPlayer*player;
-(void)appWillEnterForeground{
if(self.player){
[self.player stopPlayBackgroundAlive];
}
}
-(void)appDidEnterBackground{
if(_player==nil){
_player=[[BackgroundPlayer alloc]init];
}
[self.player startPlayer];
}