Skip to content

Instantly share code, notes, and snippets.

player.addPeriodicTimeObserver(forInterval: CMTime(seconds: 1, preferredTimescale: 2), queue: DispatchQueue.main) {[weak self] (progressTime) in
if let duration = player.currentItem?.duration {
let durationSeconds = CMTimeGetSeconds(duration)
let seconds = CMTimeGetSeconds(progressTime)
let progress = Float(seconds/durationSeconds)
DispatchQueue.main.async {
self?.progressBar.progress = progress
if progress >= 1.0 {
func rewindVideo(by seconds: Float64) {
if let currentTime = player?.currentTime() {
var newTime = CMTimeGetSeconds(currentTime) - seconds
if newTime <= 0 {
newTime = 0
}
player?.seek(to: CMTime(value: CMTimeValue(newTime * 1000), timescale: 1000))
}
}
//1. Create a URL
if let url = URL(string: "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4") {
//2. Create AVPlayer object
let asset = AVAsset(url: url)
let playerItem = AVPlayerItem(asset: asset)
let player = AVPlayer(playerItem: playerItem)
//3. Create AVPlayerLayer object
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = self.videoView.bounds //bounds of the view in which AVPlayer should be displayed
@IBDesignable class DesignableView: UIView
{
@IBInspectable var gradientColor1: UIColor = UIColor.white {
didSet{
self.setGradient()
}
}
@IBInspectable var gradientColor2: UIColor = UIColor.white {
didSet{
class CustomCollectionViewCell: UICollectionViewCell
{
//Gradient to add in the cell
private lazy var gradient: CAGradientLayer = {
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [UIColor.darkGray.cgColor, UIColor.orange.cgColor]
gradientLayer.startPoint = CGPoint(x: 0, y: 0)
gradientLayer.endPoint = CGPoint(x: 1, y: 1)
gradientLayer.frame = self.bounds
return gradientLayer
class DynamicHeightCollectionView: UICollectionView {
override func layoutSubviews() {
super.layoutSubviews()
if!__CGSizeEqualToSize(bounds.size,self.intrinsicContentSize){
self.invalidateIntrinsicContentSize()
}
}
override var intrinsicContentSize: CGSize {
return contentSize
}
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, mode: AVAudioSessionModeDefault, options: .mixWithOthers) //For playing volume when phone is on silent
} catch {
print(error.localizedDescription)
}
public func playVideo() {
player?.play()
}
public func pauseVideo() {
player?.pause()
}
func expandVideo() {
player?.pause()
let controller = AVPlayerViewController()
controller.player = player
NotificationCenter.default.addObserver(self, selector: #selector(avPlayerClosed), name: Notification.Name("avPlayerDidDismiss"), object: nil)
self.parentViewController()?.present(controller, animated: true) { in
DispatchQueue.main.async {
player?.play()
}
}
extension AVPlayerViewController {
open override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.player?.pause()
NotificationCenter.default.post(name: Notification.Name("avPlayerDidDismiss"), object: nil, userInfo: nil)
}
}