Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import UIKit
import AVKit
import AVFoundation
protocol VideViewDelegate {
func didEndVideo()
}
class VideoView: UIView {
var playerLayer: AVPlayerLayer?
var player: AVPlayer?
var isLoop: Bool = false
var delegate: VideViewDelegate!
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func configure(url: String) {
guard let path = Bundle.main.path(forResource: url, ofType: "mp4") else { return }
let videoURL = URL(fileURLWithPath: path)
player = AVPlayer(url: videoURL)
playerLayer = AVPlayerLayer(player: player)
playerLayer?.frame = bounds
playerLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
if let playerLayer = self.playerLayer {
layer.addSublayer(playerLayer)
}
NotificationCenter.default.addObserver(self, selector: #selector(reachTheEndOfTheVideo), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: self.player?.currentItem)
}
func destroyMe() {
stop()
NotificationCenter.default.removeObserver(self)
}
func play() {
if player?.timeControlStatus != AVPlayer.TimeControlStatus.playing {
player?.play()
}
}
func pause() {
player?.pause()
}
func stop() {
player?.pause()
player?.seek(to: CMTime.zero)
}
@objc
func reachTheEndOfTheVideo(_ notification: Notification) {
if isLoop {
player?.pause()
player?.seek(to: CMTime.zero)
player?.play()
} else {
if delegate != nil { delegate.didEndVideo() }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment