后台运行程序

1. 在ios8 之后, 后台能够自动播放音乐, 我自己测试过(不需要配置);

2. 在ios7中, 配置方法:

  • 2.1 在AppDelegate.m的, applicationDidEnterBackground方法中, 配置

/**

 *  进入后台 --- 继续播放

 */

- (void)applicationDidEnterBackground:(UIApplication *)application

{

    // 开启后台任务

    UIBackgroundTaskIdentifier identifier = [application beginBackgroundTaskWithExpirationHandler:^{

        [application endBackgroundTask:identifier];

    }];

}

  • 2.2 在info.plist中, 增加一项属性设置
    • Required background modes     ------------      App provides Voice over IP services 或者 App plays audio or streams audio/video using AirPlay
    • 在 播放音乐的工具类中, 设置会话类型(在initialize方法中)

/**

 *  保证soundIDs, 只创建1次

 */

+ (void)initialize

{

    // 为了保证后台播放, 设置会话类型

    // 1. 创建音频会话

    AVAudioSession *session = [[AVAudioSession alloc] init];

    

    // 2. 设置会话类型

    [session setCategory:AVAudioSessionCategoryPlayback error:nil];

    

    // 3. 激活会话

    [session setActive:YES error:nil];

}

原文地址:https://www.cnblogs.com/guangleijia/p/4839231.html