Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to present a full screen AVPlayerViewController in SwiftUI

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?

like image 451
Rik Avatar asked Jan 20 '26 15:01

Rik


1 Answers

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
    }
}
like image 111
Asperi Avatar answered Jan 23 '26 15:01

Asperi