In my app, I have multiple tabs and on each tab I have an instance of AVPlayer. When I activate AirPlay, however, "the first player wins". That means that the player on the currently active tab connects to AirPlay and when I switch to a different tab and press play, nothing happens. So only the first instance of AVPlayer that connects to AirPlay can actually play through AirPlay and no players on the other tabs work. What to do?
Asked
Active
Viewed 1,845 times
2
-
Out of curiosity, why not use the singleton pattern for your AVPlayer? – Marco Nov 05 '13 at 22:17
-
@Marco: That is one possibility, but I'd rather not have to "manually" remember and restore the state of each player on each tab, but have separate players that do that for me. – Johannes Fahrenkrug Nov 06 '13 at 13:33
1 Answers
3
The solution is quite easy: When your view controller that contains a player appears, you set allowsExternalPlayback
on the AVPlayer instance to YES
, when in disappears you set it to NO
.
Example:
- (void)viewWillAppear:(BOOL)animated
{
// _player is an instance of AVPlayer
if ([_player respondsToSelector:@selector(setAllowsExternalPlayback:)]) {
// iOS 6+
_player.allowsExternalPlayback = YES;
} else {
// iOS 5
_player.allowsAirPlayVideo = YES;
}
[super viewWillAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
// _player is an instance of AVPlayer
if ([_player respondsToSelector:@selector(setAllowsExternalPlayback:)]) {
// iOS 6+
_player.allowsExternalPlayback = NO;
} else {
// iOS 5
_player.allowsAirPlayVideo = NO;
}
[super viewWillDisappear:animated];
}
Enjoy.

Johannes Fahrenkrug
- 42,912
- 19
- 126
- 165