2

In SwiftUI, it seems like the best way to set up an AVPlayerViewController is to use the UIViewControllerRepresentable in a fashion somewhat like this...

struct PlayerViewController: UIViewControllerRepresentable {
    var videoURL: URL?


    private var player: AVPlayer {
        return AVPlayer(url: videoURL!)
    }


    func makeUIViewController(context: Context) -> AVPlayerViewController {
        let controller =  AVPlayerViewController()
        controller.modalPresentationStyle = .fullScreen
        controller.player = player
        controller.player?.play()
        return controller
    }

    func updateUIViewController(_ playerController: AVPlayerViewController, context: Context) {

    }
}

However from the documentation that the only way to show this controller in a full-screen way is to present it using a sheet.

.sheet(isPresented: $showingDetail) {
    PlayerViewController(videoURL: URL(string: "..."))
      .edgesIgnoringSafeArea(.all)
}

This doesn't give you a full-screen video with a dismiss button but a sheet modal which can be swiped away instead.

In standard non-SwiftUI Swift, it would seem like the best way would be to present this controller...

let controller = PlayerViewController(videoURL: URL(string: "..."))
self.present(controller, animated: true)

...but SwiftUI doesn't have a self.present as part of it. What would be the best way to present a full-screen video in SwiftUI?

Rik
  • 95
  • 2
  • 7
  • This answer could help you, you can change the style and presentation mode as you like. https://stackoverflow.com/questions/60391281/how-to-present-crossdissolve-view-in-swiftui/60403229#60403229 – Mac3n Apr 20 '20 at 20:40
  • Apple added support for full screen views in SwiftUI. It works for me using an UIImagePickerView, so it might work with your AVPlayerView/Controller as well. See my answer here: https://stackoverflow.com/a/64069283/3997690 – LaX Sep 25 '20 at 18:09
  • https://developer.apple.com/forums/thread/131762 – Anurag Sharma Jan 21 '21 at 10:54

1 Answers1

2

Instead of sheet I would use the solution with ZStack (probably with custom transition if needed), like below

ZStack {
    // ... other your content below

    if showingDetail { // covers full screen above all
       PlayerViewController(videoURL: URL(string: "..."))
         .edgesIgnoringSafeArea(.all)
         //.transition(AnyTransition.move(edge: .bottom).animation(.default)) // if needed
    }
}
Asperi
  • 228,894
  • 20
  • 464
  • 690
  • Thank you! Makes a lot of sense and wish it was clearer in the docs! – Rik Apr 25 '20 at 19:08
  • Any advice on how to use this to show full screen and also be able to close video player with a swipe down, also close the player using an X button etc? – Jonny Sep 02 '22 at 10:30