iOS 9.1 - iPhone 6S
MPVolumeView's route button (airplay) is not showing when app launches even when there are wireless routes available.
I have tried querying my MPVolumeView after it has been created to check for wireless routes and I get 0. I'm only able to get 1 (and have the route button appear) by disabling and enabling WiFi to trigger a notification.
The MPVolumeView in my app is to control the volume of videos played from UIWebView. Also, whenever I activate a wireless route for streaming the MPVolumeView slider disappears - is there a way to prevent this behaviour when using UIWebView to play media?
Below is my code for creating the MPVolumeView:
-(void) createAndDisplayMPVolumeView{
// Create a simple holding UIView and give it a frame
volumeHolder = [[UIView alloc] initWithFrame: volumeSlider.frame];
volumeHolder.autoresizingMask = UIViewAutoresizingFlexibleHeight;
volumeSlider.hidden = YES;
// set the UIView backgroundColor to clear.
[volumeHolder setBackgroundColor: [UIColor clearColor]];
// add the holding view as a subView of the main view
[nowPlayingMainView addSubview: volumeHolder];
// Create an instance of MPVolumeView and give it a frame
myVolumeView = [[CustomVolumeView alloc] initWithFrame: volumeHolder.bounds];
myVolumeView.tintColor = [UIColor darkTextColor];
myVolumeView.showsRouteButton = YES;
myVolumeView.showsVolumeSlider = YES;
volumeRect = myVolumeView.frame;
[myVolumeView setRouteButtonImage:[UIImage imageNamed:@"airplayButton"] forState:UIControlStateNormal];
[myVolumeView setRouteButtonImage:[UIImage imageNamed:@"airplayButtonHighlighted"] forState:UIControlStateHighlighted];
[myVolumeView setRouteButtonImage:[UIImage imageNamed:@"airplayButtonSelected"] forState:UIControlStateSelected];
[volumeHolder addSubview: myVolumeView];
}
As @kvr said, first test on hardware device
Airplay route button appears when more than one route is available.
Trick I found to show permanently Airplay Button is to hide MPVolumeView route button, remove user MPVolumeView user interaction and target the route button action with a UIButton Wrapper.
var airplayRouteButton: UIButton?
private func airPlayButton() -> UIButton {
let wrapperView = UIButton(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
wrapperView.setImage(YOUR_AIRPLAY_IMAGE, for: UIControlState.normal)
wrapperView.backgroundColor = .clear
wrapperView.addTarget(self, action: #selector(PlayerView.replaceRouteButton), for: UIControlEvents.touchUpInside)
let volumeView = MPVolumeView(frame: wrapperView.bounds)
volumeView.showsVolumeSlider = false
volumeView.showsRouteButton = false
volumeView.isUserInteractionEnabled = false
self.airplayRouteButton = volumeView.subviews.filter { $0 is UIButton }.first as? UIButton
wrapperView.addSubview(volumeView)
return wrapperView
}
@objc private func replaceRouteButton() {
airplayRouteButton?.sendActions(for: .touchUpInside)
}
来源:https://stackoverflow.com/questions/35925850/mpvolumeview-does-not-show-route-button-on-launch