iOS SwiftUI video autoplay

Viewed 2030

I'm working on an iOS app that has a set of buttons on one view, when one of the buttons is tapped, the app navigates to a new view of a video and should autoplay the video. The video is currently not autoplaying, but will play on tap, my understanding is the video should autoplay with the code below. Any help is appreciated (this is my first time building an iOS app).

let player = AVPlayer(url: URL(fileURLWithPath: Bundle.main.path(forResource: "videoToPlay", ofType: "mp4")!))

VideoPlayer(player: player)
  .edgesIgnoreSafeArea(.all)
  .onAppear() {
    player.play()
}
3 Answers

I had the same problem when autoplaying from a sheet. I solved it by loading the video item in the onAppear and playing it after the view appeared like this:

var player = AVPlayer()

VideoPlayer(player: player)
    .onAppear{
      if player.currentItem == nil {
            let item = AVPlayerItem(url: URL(string: url)!)
            player.replaceCurrentItem(with: item)
        }
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: {
            player.play()
        })
    }

You're right, the following code does work, but probably doesn't behave as you expect because of the way that .onAppear works within SwiftUI. Unless your video is inside some form of lazy view, and is off-screen til scrolled, then .onAppear will run on initial render of the view.

You don't state your use-case, but I'd suggest that you might be able to achieve something using timers, or alternatively some sort of UIKit adaptation. Best of luck!

I did it with following setup.

I have a list with LazyVStack

ScrollView{
    LazyVStack {
        ForEach(posts, id: \.id) { post in
            buildPostCell(post)
        }
    }
}

Inside the cell. vm.player is a lazy AVPlayer variable, implemented per cell in viewmodel

VideoPlayer(player: vm.player)
    .frame(height: 300)
    .onAppear {
        vm.player?.play()
    }.onDisappear {
        vm.player?.pause()
    }
Related