Skip to content

Instantly share code, notes, and snippets.

@arbyruns
Created September 11, 2022 14:45
Show Gist options
  • Save arbyruns/907efd4c5d403b06ced44018ac073ec4 to your computer and use it in GitHub Desktop.
Save arbyruns/907efd4c5d403b06ced44018ac073ec4 to your computer and use it in GitHub Desktop.
AVPlayer
let player = AVPlayer(url: URL(string: videoURL.url)!)
VideoPlayer(player: player)
.onAppear {
playerLayer.backgroundColor = UIColor.blue.cgColor
addObserver(player: player) // 1
}
.onDisappear {
removeObserver()
player.pause()// 2
}
.frame(width: 300, height: 450)
func addObserver(player: AVPlayer) {
NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime,
object: player.currentItem,
queue: nil) { notif in // 3
player.seek(to: .zero) // 4
player.play() // 5
}
}
func removeObserver() {
NotificationCenter.default.removeObserver(self, // 6
name: .AVPlayerItemDidPlayToEndTime,
object: nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment