【iOS系列】-程序开启后台运行

【iOS系列】-程序开启后台运行

iOS程序是伪后台的运行,可是有时候我们需要让其在后台也要进行一些操作,我们可以让其伪装成音乐的APP,这样就可以让程序后台进行相关操作了,具体做法如下:

1:在AppDelegate.m的applicationDidEnterBackground方法中开启后台任务
- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // 开启后台任务,让程序保持运行状态
    [application beginBackgroundTaskWithExpirationHandler:nil];
}
2:在info.plist中添加程序的音乐标示

新建一个:Required background modes类型的NSArray
并在子类目下新建一个Item 0 其value为App plays audio or streams audio/video using AirPlay

3: 设置AVAudioSession类型
    // 设置音频会话类型
    AVAudioSession *session = [AVAudioSession sharedInstance];
       //AVAudioSessionCategorySoloAmbient:官方解释, Use this category for background sounds.  Other music will stop playing,也即这个APP播放的时,其他APP会停止播放
    [session setCategory:AVAudioSessionCategorySoloAmbient error:nil];
    [session setActive:YES error:nil];
原文地址:https://www.cnblogs.com/fengtengfei/p/4472399.html