iOS - AVAudioSession Route Change Notification in

2019-02-12 18:09发布

问题:

Despite many posts on the subject (AVPlayer & AVAudioSession, Setting the AVAudioSession category in AppDelegate.m, AvAudioSession won't work in iOS7?), I could not solve this specific issue in iOS 7:
- I want to receive AVAudioSession Route Change notifications while in the background
- my app is not playing any music at any point, and should not interfere with other apps playing sound

The setup:
- audio enabled in p-list UIBackgroundModes
- in the main controller:

// AUDIO
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayback  withOptions:AVAudioSessionCategoryOptionMixWithOthers error:nil];
[audioSession setActive:YES error:nil];

// NOTIFICATIONS
[[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(audioSessionRouteChanged:)
                                                 name:AVAudioSessionRouteChangeNotification
                                               object:nil];

This works fine in foreground, so I must be missing something simple to enable background notifications. I have tried several different categories starting with AVAudioSessionCategoryAmbient, with no luck.

Is there a restriction to only receive background notifications when playing sound?

Thanks for your help!

UPDATE There needs to be an AVPlayer playing to receive notifications in background. So this is unfortunately not doable, expect by playing a silent track, which is not Apple accepted...

回答1:

If you're in the background and not playing music, your app is suspended. You can't receive notifications or anything else. If there are any notifications for you, they will be delivered when your app is activated again.