7

Using AVRoutePickerView, I'm able to do the Airplay programmatically upon tapping the Airplay icon. Now I want, on viewDidLoad it should initialize the AVRoutePickerView and even tap the airplay icon (no need to manually tap on icon).

Here's my small piece of code to display Airplay icon on UIView

let routePV = AVRoutePickerView(frame: CGRect(x: 30.0, y: 150.0, width: 30.0, height: 30.0)) routePV = UIColor.clear
self.view.addSubview(routePV)

I'm really not sure how to trigger tap on viewdidload ?

Thanks

janubhai
  • 183
  • 1
  • 8

2 Answers2

10

This is possible. However I must caution it is likely to be quite unexpected behavior to present this interface without user interaction. I’d recommend only doing this as a direct result of the user intending to present this interface.

Make sure you have added it to your view hierarchy.

let routePickerView = AVRoutePickerView()
view.addSubview(routePickerView)

If desired, you can hide it.

routePickerView.isHidden = true

Then to present the route picker interface, trigger touchUpInside on its UIButton:

if let routePickerButton = routePickerView.subviews.first(where: { $0 is UIButton }) as? UIButton {
    routePickerButton.sendActions(for: .touchUpInside)
}

Do note that this could stop working in a future iOS release.

Jordan H
  • 52,571
  • 37
  • 201
  • 351
  • could you please tell me why it will not work on future release because I am implementing AirPlay. Thanks! – Yogesh Patel Mar 04 '21 at 18:30
  • 1
    @YogeshPatel It might stop working because it’s a bit of a hack to find the button and manually trigger it – Jordan H Mar 04 '21 at 19:10
  • Thanks for your response. I just added a question regarding this topic. Could you please check and answer that if possible. Thanks! https://stackoverflow.com/questions/66481231/how-to-add-an-airplay-button-to-an-app-in-swift-5 – Yogesh Patel Mar 04 '21 at 19:13
5

I prefer to use an extension:

fileprivate extension AVRoutePickerView {
    func present() {
        let routePickerButton = subviews.first(where: { $0 is UIButton }) as? UIButton
        routePickerButton?.sendActions(for: .touchUpInside)
    }
}

Example implementation:

class RandomViewController: UIViewController {

    ...

    private lazy var routePickerView = { 
        let routePickerView = AVRoutePickerView(frame: .zero)
        routePickerView.isHidden = true
        view.addSubview(routePickerView)
        return routePickerView
    }

    ...

    @IBAction func presentPickerView(_ sender: UIButton) {
        routePickerView.present()
    }
}
Stefan
  • 131
  • 1
  • 1