I need to show Avplayer in CollectionviewCell with Loading view(activity indicator). Below are the code what I try
UIcollectionViewCell:- cell content view contains view & some buttons(like, comment,share) in view I need to show avplayer.Videodict is array of dictionary.
Every time I scroll I will call web service get another dictionary & appending in VideoDict
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! UICollectionViewCell
let playerView = cell.contentView.viewWithTag(1)
player = AVPlayer(url: URL(string: videodict[indexPath.item]["vid_url"] as! String)!)
playerLayer = AVPlayerLayer(player: player)
playerLayer?.frame = cell.contentView.frame
playerLayer?.videoGravity = .resizeAspectFill
playerView!.layer.addSublayer(playerLayer!)
player?.currentItem!.addObserver(self, forKeyPath: "“timeControlStatus”", options: [.old, .new], context: nil)
player?.play()
return cell
}
ObserverMethod
override public func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?)
{
if keyPath == "timeControlStatus", let change = change, let newValue = change[NSKeyValueChangeKey.newKey] as? Int,let oldValue = change[NSKeyValueChangeKey.oldKey] as? Int
{
let oldStatus = AVPlayer.TimeControlStatus(rawValue: oldValue)
let newStatus = AVPlayer.TimeControlStatus(rawValue: newValue)
if newStatus != oldStatus
{
DispatchQueue.main.async {[weak self] in
if newStatus == .playing || newStatus == .paused
{
LoaderView.show()
}
else
{
LoaderView.hide()
}
}
}
}
}
Videos are playing in CollectionViewCell but ObserverValue Function not calling & is any best way to play videos in collection view.
Try observing
timeControlStatusas following:Do not forget to call
timeControlStatusObserver.invalidate()after you class is deinitialized indeinit.