Reputation: 17169
I have started using MPVolumeView
in my app, however the Air Play button doesn't appear at all. Even though I have more than one Air Play device available to send my AVPlayer
audio to on the network. These can be seen if checking Air Play from the Control Center for example.
Here is the code I have:
myVolumeView = [MPVolumeView new];
[myVolumeView setShowsVolumeSlider:YES];
[myVolumeView setShowsRouteButton:YES];
myVolumeView.frame = _volumePanel.bounds;
[myVolumeView sizeToFit];
_myVolumeView.autoresizingMask = UIAutoresizingFlexibleWidth;
[_volumePanel addSubview:myVolumeView];
Pretty simple stuff. I have an AVPlayer
that runs some music and that's it. Interestingly, if I select another Air Play device from the Control Center it forces the Air Play button to appear in app on my MPVolumeView
, but it is kind of glitchy.
If in Xcode I click the Debug Hierarchy Mode button above the console I can see the Air Play button in my UI, however it's Alpha is 0.
Upvotes: 8
Views: 1843
Reputation: 1979
[Swift Version]
Create following functions:
func fixAirPlayButton() {
guard let routeButton = airPlayButton.subviews.filter({$0 is UIButton}).first else { return }
routeButton.addObserver(self, forKeyPath: "alpha", options: .new, context: nil)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
guard let btnObject = object as? UIButton, let change = change else { return}
guard let newChange = change[NSKeyValueChangeKey.newKey] as? Int, newChange != 1 else { return }
btnObject.alpha = 1.0
}
func removeAirPlayButtonFix() {
guard let routeButton = airPlayButton.subviews.filter({$0 is UIButton}).first else { return }
routeButton.removeObserver(self, forKeyPath: "alpha")
}
And use them when needed, example:
let airPlayButton = MPVolumeView(frame: .zero)
override func viewDidLoad() {
super.viewDidLoad()
fixAirPlayButton()
}
deinit {
removeAirPlayButtonFix()
}
Upvotes: 0
Reputation: 173
it's a complete and utter hack but it works
MPVolumeView* airplayButton = [[MPVolumeView alloc] init];
for (UIButton *button in airplayButton.subviews)
{
if ([button isKindOfClass:[UIButton class]])
{
[button addObserver:self forKeyPath:@"alpha" options:NSKeyValueObservingOptionNew context:nil];
}
}
Then in the observer
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([object isKindOfClass:[UIButton class]] && [[change valueForKey:NSKeyValueChangeNewKey] intValue] != 1)
{
UIButton *airplay = (UIButton *)object;
[airplay setAlpha:1.0];
}
}
don't forget to turn the observer off in the dealloc
- (void)dealloc
{
for (UIButton *button in _airplayButton.subviews)
{
if ([button isKindOfClass:[UIButton class]])
{
[button removeObserver:self forKeyPath:@"alpha"];
break;
}
}
}
Upvotes: 2