I have a list of URLs in SwiftUI. When I tap an item, I present a full screen video player. I have an @EnvironmentObject
that handles some viewer options (for example, whether to show a timecode). I also have a toggle that shows and hides the timecode (I've only included the toggle in this example as the timecode view doesn't matter) but every time I change the toggle the view is created again, which re-sets the AVPlayer
. This makes sense since I'm creating the player in the view's initialiser.
I thought about creating my own ObserveredObject
class to contain an AVPlayer
but I'm not sure how or where I'd initialise it since I need to give it a URL, which I only know from the initialiser of CustomPlayerView
. I also thought about setting the player as an @EnvironmentObject
but it seems weird to initialise something I might not need (if the user doesn't tap on a URL to start the player).
What is the correct way to create an AVPlayer
to hand to AVKit's VideoPlayer
please? Here's my example code:
class ViewerOptions: ObservableObject {
@Published var showTimecode = false
}
struct CustomPlayerView: View {
@EnvironmentObject var viewerOptions: ViewerOptions
private let avPlayer: AVPlayer
init(url: URL) {
avPlayer = AVPlayer(url: url)
}
var body: some View {
HStack {
VideoPlayer(player: avPlayer)
Toggle(isOn: $viewerOptions.showTimecode) { Text("Show Timecode") }
}
}
}