How to show AVPlayer in UICollectionViewcell with Loader

522 views Asked by At

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.

1

There are 1 answers

0
Mr.SwiftOak On

Try observing timeControlStatus as following:

    var timeControlStatusObserver: NSKeyValueObservation?
    timeControlStatusObserver = self.avPlayer.observe(\.timeControlStatus, options: [.new, .initial], changeHandler: {[weak self] (player, status) in
        if let self = self,let status = status.newValue {
            switch status {
            case .paused:
                print("status paused")
            case .waitingToPlayAtSpecifiedRate:
                print("status waitingToPlayAtSpecifiedRate")
            case .playing:
                print("status playing")
            @unknown default:
                print("status unknown")
            }
        }
    })

Do not forget to call timeControlStatusObserver.invalidate() after you class is deinitialized in deinit.