后台播放音乐(1)——设置后台任务

+ (UIBackgroundTaskIdentifier)backgroundPlayerID:(UIBackgroundTaskIdentifier)backTaskId

{

    // 1. 设置并激活音频会话类别

       AVAudioSession *session = [AVAudioSession sharedInstance];

    [session AVAudioSessionCategoryPlayback error:nil];

    [session setActive:YES error:nil];

    // 2. 允许应用程序接收远程控制

    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

    // 3. 设置后台任务ID

      UIBackgroundTaskIdentifier newTaskId = UIBackgroundTaskInvalid;

    newTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];

    if (newTaskId != UIBackgroundTaskInvalid && backTaskId != UIBackgroundTaskInvalid) {

        [[UIApplication sharedApplication] endBackgroundTask:backTaskId];

    }

    return newTaskId;

}

注意:后台播放音乐(2)——允许后台播放

原文地址:https://www.cnblogs.com/changxs/p/3468306.html