So trying to implement as simple observer for AVPlayer in SwiftUI. I've added the observer which is triggered but haven't figured out how/where to implement observeValue as per the Apple documentation: https://developer.apple.com/documentation/avfoundation/media_assets_playback_and_editing/responding_to_playback_state_changes
So far I have my AVPlayer class as follows:
class Player: AVPlayer, ObservableObject {
@Published var isPlaying: Bool = false
static var shared = AVPlayer()
static var episodeId: Int?
static func playItem(at itemURL: String, episodeId: Int) {
let url = URL(string: itemURL)
Player.shared = AVPlayer(url: url!)
Player.episodeId = episodeId
Player.shared.addObserver(self.shared, forKeyPath: "timeControlStatus", options: [.old, .new], context: nil)
}
}
So the question is where I should implement this for it to work:
override func observeValue(forKeyPath keyPath: String?,
of object: Any?,
change: [NSKeyValueChangeKey : Any]?,
context: UnsafeMutableRawPointer?) {
if Player.shared.timeControlStatus == .playing {
// Set @Published isPlaying to true
}
}