2

I am using QueuePlayer to play a list of songs and the songs are playing. My issue is that I am trying to track whenever the current item changes. I try adding an observer to the QueuePlayer, but this isn't working. The observing func isn't getting called. Any help would be appreciated

Observer

 queuePlayer.currentItem?.addObserver(self, forKeyPath: "currentItem", options: [.new, .old], context: nil)
    }

Listening for observer // Not getting called when item changes

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if keyPath == "currentItem" {
        if let oldItem = change?[NSKeyValueChangeKey.oldKey] as? AVPlayerItem {
            print("Old item : \(oldItem)")
        }

        if let newItem = change?[NSKeyValueChangeKey.newKey] as? AVPlayerItem {
            print("New item : \(newItem)")
        }    
    }
}
Iam Wayne
  • 561
  • 6
  • 26

2 Answers2

2

Your code is observing the currentItem property of queuePlayer.currentItem.

To observe the currentItem property of queuePlayer, it should be

queuePlayer.addObserver(self, forKeyPath: "currentItem", …

or better yet, for compile time checking…

queuePlayer.addObserver(self, forKeyPath: #keyPath(AVQueuePlayer.currentItem), …
Ashley Mills
  • 50,474
  • 16
  • 129
  • 160
  • thanks for your response. I tried your answer "queuePlayer.addObserver(self, forKeyPath: "currentItem", … This didn't work, observer function still not getting called. – Iam Wayne Aug 21 '18 at 17:26
-1

If you need to know when an item finished playing, you can go something like.

Inside your viewdidload(), add observer

NotificationCenter.default.addObserver(self, selector: #selector(itemDidPlayToEnd), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)

@objc func itemDidPlayToEnd() {

    //your item played to end
  }

I Just verified that its working fine

This may also be helpful

Awais Fayyaz
  • 2,275
  • 1
  • 22
  • 45