Malav Soni
Malav Soni

Reputation: 2848

How to show play button when video ends in AVPlayer in SwiftUI

I am trying to show the default play icon when the video ends. As default behavior, it shows all the other control like shown in 2nd image but I want the play button the same as 1st image.

enter image description here enter image description here

I am using the below code for it.

struct AVPlayerView: UIViewControllerRepresentable {
    
    var videoURL: URL
    @State var playerController:AVPlayerViewController?
    @State var player:AVPlayer?
    
    func makeUIViewController(context: UIViewControllerRepresentableContext<AVPlayerView>) -> AVPlayerViewController {
        
        let controller = AVPlayerViewController()
        controller.player = AVPlayer(url: videoURL)
        controller.videoGravity = .resizeAspect
        
        self.player = controller.player
        self.playerController = controller
        
        return controller
    }

    func updateUIViewController(_ uiViewController: AVPlayerViewController, context: UIViewControllerRepresentableContext<AVPlayerView>) {
    }
}

I am planning to re-init AVPlayer when video ends but not sure if that's the correct way.

Upvotes: 1

Views: 1037

Answers (1)

Malav Soni
Malav Soni

Reputation: 2848

Here is what I did and it worked well.

struct AVPlayerView: UIViewControllerRepresentable {

    var videoURL: URL
    let controller = AVPlayerViewController()

    func makeUIViewController(context: UIViewControllerRepresentableContext<AVPlayerView>) -> AVPlayerViewController {
        
        controller.player = AVPlayer(url: videoURL)
        controller.videoGravity = .resizeAspect
        
        self.addPeriodicTimeObserver()
        
        return controller
    }

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

    }

    func addPeriodicTimeObserver() {
        self.controller.player?.addPeriodicTimeObserver(forInterval: CMTime(seconds: 1, preferredTimescale: CMTimeScale(NSEC_PER_SEC)), queue: DispatchQueue.main, using: { (currentTime) in
            if let endTime = self.controller.player?.currentItem?.duration {
                if currentTime == endTime {
                    // Reset the player
                    self.controller.player = AVPlayer(url: self.videoURL)
                    self.addPeriodicTimeObserver()
                }
            }
        })
    }
}

Upvotes: 2

Related Questions