Reputation: 13085
I can use this to add an Airplay button to my view:
AirPlayView()
.frame(width: 44, height: 44)
...
struct AirPlayView: UIViewRepresentable {
func makeUIView(context: Context) -> UIView {
let routePickerView = AVRoutePickerView()
routePickerView.backgroundColor = UIColor.clear
routePickerView.activeTintColor = UIColor.red
routePickerView.tintColor = UIColor.white
return routePickerView
}
func updateUIView(_ uiView: UIView, context: Context) {
}
}
When the user selects an external screen (TV/computer), the currently playing video disappears from my UI and is cast to the external screen, but my UI is left blank. I need to display a "Connected to Airplay" text or something in the empty space. How can I respond to the user entering and leaving airplay mode in SwiftUI?
Upvotes: 0
Views: 680
Reputation: 25
You have to use AVPlayer.isExternalPlaybackActive
and observe its changes. Since you're using SwiftUI, you'd probably be familiar with this Combine approach:
// [...]
let player = AVPlayer()
var bag = Set<AnyCancellable>()
// [...]
func setupPlayerPublisher() {
player
.publisher(for: \.isExternalPlaybackActive)
.sink(receiveValue: { [weak self] isExternalPlaybackActive in
guard isExternalPlaybackActive else {
// handle UI for playing video on the device
return
}
// handle UI for AirPlay
})
.store(in: &bag)
}
Then call setupPlayerPublisher()
where it fits with your needs.
Upvotes: 1