Proper UIKit Approach:
According to Apple's WWDC 2019 talk on the subject, AVPlayerViewController
should be presented modally to take advantage of all the latest full-screen features of the API. This is the recommended sample code to be called from your presenting UIKit view controller:
// Create the player
let player = AVPlayer(url: videoURL)
// Create the player view controller and associate the player
let playerViewController = AVPlayerViewController()
playerViewController.player = player
// Present the player view controller modally
present(playerViewController, animated: true)
This works as expected and launches the video in beautiful full-screen.
Achieve the Same Effect with SwiftUI?:
In order to use the AVPlayerViewController
from SwiftUI, I created the UIViewControllerRepresentable
implementation:
struct AVPlayerView: UIViewControllerRepresentable {
@Binding var videoURL: URL
private var player: AVPlayer {
return AVPlayer(url: videoURL)
}
func updateUIViewController(_ playerController: AVPlayerViewController, context: Context) {
playerController.player = player
playerController.player?.play()
}
func makeUIViewController(context: Context) -> AVPlayerViewController {
return AVPlayerViewController()
}
}
I cannot seem to figure out how to present this directly from SwiftUI in the same way as the
AVPlayerViewController
is presented directly from UIKit. My goal is simply to get all of the default, full-screen benefits.
So far, the following has not worked:
- If I use a
.sheet
modifier and present it from within the sheet, then the player is embedded in a sheet and not presented full-screen. - I have also tried to create a custom, empty view controller in UIKit that simply presents my
AVPlayerViewController
modally from theviewDidAppear
method. This gets the player to take on the full screen, but it also shows an empty view controller prior to display the video, which I do not want the user to see.
Any thoughts would be much appreciated!