6

How can I display an AirPlay popup menu in my Swift project? (Many applications like Spotify can display one like below):

enter image description here

1
  • Look at adding a 'MPVolumeView' to your app. You don't actually create the menu but by having that control it will allow the user to see that menu when they click on it.
    – totiDev
    Commented Jul 3, 2017 at 6:52

2 Answers 2

10

After all it seems there is no easy and straightforward way to make a custom button display the system's Airplay menu.

However, @totiG pointer me to an interesting resource and I created a script that creates the standard Volume Control outside of the visible area of the screen a simulates a click on the Airplay button:

func showAirplay() {
    let rect = CGRect(x: -100, y: 0, width: 0, height: 0)
    let airplayVolume = MPVolumeView(frame: rect)
    airplayVolume.showsVolumeSlider = false
    self.view.addSubview(airplayVolume)
    for view: UIView in airplayVolume.subviews {
        if let button = view as? UIButton {
            button.sendActions(for: .touchUpInside)
            break
        }
    }
    airplayVolume.removeFromSuperview()
}

After running this code the following popup menu appears:

enter image description here

2
  • Using this code I got only transparent rect without any slider or button. Commented Aug 6, 2017 at 5:14
  • @SergeyDi: I have added a screenshot above to show what this code does in my environment. Doesn't it work the same way for you? What iOS version are you running? Commented Aug 7, 2017 at 6:13
4

Here's a sweet little workaround to having to use the MPVolumeView's button.

  1. Create a MPVolumeView, and hide it somewhere in the view hierarchy.
  2. Whenever you want to display the picker:

[[UIApplication sharedApplication] sendAction:NSSelectorFromString(@"_displayAudioRoutePicker") to:myVolumeView from:myView forEvent:nil];

Optional 3: On iPad you'll need to pass a UIEvent otherwise the popover will just be entered at the top of the screen and it'll look wonky. Capture the event from - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event; and pass it into our call.

1
  • I know this is a bit late, but is this a private API? (Will my app be accepted to the app store if I use this?)
    – Minebomber
    Commented Sep 4, 2017 at 14:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.