/* Swift 3.0, Add Observers */
func setupPlayerObservers(){
player.addObserver(self, forKeyPath: "currentItem.loadedTimeRanges", options: .new, context: nil)
player.addObserver(self, forKeyPath: "rate", options: [.new], context: nil)
player.currentItem?.addObserver(self, forKeyPath: "status", options: [.old, .new], context: nil)
player.currentItem?.addObserver(self, forKeyPath: "playbackBufferEmpty", options: [.old, .new], context: nil)
player.currentItem?.addObserver(self, forKeyPath: "playbackLikelyToKeepUp", options: [.old, .new], context: nil)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
//this is when the player is ready and rendering frames
if keyPath == "currentItem.loadedTimeRanges" {
if !hasLoaded {
activityIndicatorView.stopAnimating()
Mixpanel.mainInstance().track(event: "Play", properties: ["success": true, "type": "clip"])
}
hasLoaded = true
}
if keyPath == "rate" {
if player.rate == 0.0 {
playPauseButton.setImage(UIImage(named: "PlayButton"), for: UIControlState())
} else {
playPauseButton.setImage(UIImage(named: "PauseButton"), for: UIControlState())
}
}
if keyPath == "status" {
// Do something here if you get a failed || error status
}
if keyPath == "playbackBufferEmpty" {
let time = Int(CMTimeGetSeconds(player.currentTime()))
bufferingCount += 1
if bufferingCount % 4 == 0 {
Mixpanel.mainInstance().track(event: "VideoBuffered", properties: ["numTimes": bufferingCount, "type": "clip", "currentTime": time])
}
activityIndicatorView.isHidden = false
activityIndicatorView.startAnimating()
}
if keyPath == "playbackLikelyToKeepUp" {
activityIndicatorView.isHidden = true
activityIndicatorView.stopAnimating()
}
}
/* Remove observers in deinit */
deinit {
player.removeTimeObserver(timeObserver)
player.removeObserver(self, forKeyPath: "currentItem.loadedTimeRanges")
player.removeObserver(self, forKeyPath: "rate")
player.currentItem?.removeObserver(self, forKeyPath: "playbackBufferEmpty")
player.currentItem?.removeObserver(self, forKeyPath: "playbackLikelyToKeepUp")
player.currentItem?.removeObserver(self, forKeyPath: "status")
}