Reputation: 3
I am trying to get the VideoPlayer
to autoplay with the video controller but I can't seem to figure it out! What should I do? I am fairly new to SwiftUI.
struct VideoView: View {
// MARK: - PROPERTIES
//: BINDING
@Binding var videoView: Bool
//: STATE
@State var player = AVPlayer()
@State var isplaying = true
@State var showcontrols = true
//: VAR
var allowsPictureInPicturePlayback : Bool = true
var wrkflw: Wrkflw
// MARK: - BODY
var body: some View {
VideoPlayer(wrkflw: wrkflw, player: $player)
.edgesIgnoringSafeArea(.all)
.onAppear {
player.play()
}
}
}
MARK: - VIDEO CONTROLLER
struct VideoPlayer : UIViewControllerRepresentable {
var wrkflw: Wrkflw
@Binding var player : AVPlayer
func makeUIViewController(context: Context) -> UIViewController {
let player = AVPlayer(url: wrkflw.wrkvideo)
let controller = AVPlayerViewController()
controller.player = player
controller.showsPlaybackControls = true
controller.exitsFullScreenWhenPlaybackEnds = true
controller.allowsPictureInPicturePlayback = true
return controller
}
func updateUIViewController(_ uiViewController: UIViewController, context: Context) {
}
}
Upvotes: 0
Views: 1064
Reputation: 52357
The simplest solution would be to just pass the AVPlayer
reference from your VideoView
to the VideoPlayer
. You can use player.replaceCurrentItem
so that you can set the correct URL but maintain the same player reference.
Make sure you remove the let player...
lines in VideoPlayer
struct VideoView: View { // MARK: - PROPERTIES
//: BINDING
@Binding var videoView: Bool
//: STATE
@State var player = AVPlayer()
@State var isplaying = true
@State var showcontrols = true
//: VAR
var allowsPictureInPicturePlayback : Bool = true
var wrkflw: Wrkflw
// MARK: - BODY
var body: some View {
VideoPlayer(wrkflw: wrkflw, player: player)
.edgesIgnoringSafeArea(.all)
.onAppear {
player.replaceCurrentItem(with: AVPlayerItem(url: wrkflw.wrkvideo)) //<-- Here
player.play()
}
}
}
// MARK: - VIDEO CONTROLLER
struct VideoPlayer : UIViewControllerRepresentable {
var wrkflw: Wrkflw
var player : AVPlayer
func makeUIViewController(context: Context) -> UIViewController {
//<-- Here
let controller = AVPlayerViewController()
controller.player = player
controller.showsPlaybackControls = true
controller.exitsFullScreenWhenPlaybackEnds = true
controller.allowsPictureInPicturePlayback = true
return controller
}
func updateUIViewController(_ uiViewController: UIViewController, context: Context) {
}
}
Upvotes: 1