Created
April 1, 2020 16:47
-
-
Save miff/9a8c4a53dcd08e0857bcab58bacf9134 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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