I'm trying to make a custom player to SoundCloud and as there is no native support for a full fledged player in Swift-iOS (forward & backward) functionality; I then decided to use AVPlayer instead of AVQueuePlayer.
I have a Tracks class which holds relevant information about my tracks (Url's). A TracksQueue which has relevant info about the queue - multiple tracks & if I can forward or reverse logic by checking array indices of tracks array.
I have also enabled background mode in App settings as well as added the following code as many had suggested to do so while App launches in my ViewController's viewDidLoad()
UIApplication.shared.beginReceivingRemoteControlEvents()
Everything is working as expected but only problem is the track will change in background but it will not play.
All I do is remove observers from AVPlayer and initiate a new one, and replace current item with new AVPlayerItem upon NSNotification.Name.AVPlayerItemDidPlayToEndTime notification.
fileprivate func restartCurrentTrack() {
if (player != nil) {
player?.removeObserver(self, forKeyPath: Keys.Status, context: &PGAudioPlayerManagetKVOContext)
}
if let _currentTrack = queue.currentTrack {
player = AVPlayer()
player.addObserver(self, forKeyPath: Keys.Status, options: NSKeyValueObservingOptions.new, context: &PGAudioPlayerManagetKVOContext)
if let _playerItem = _currentTrack.getPlayerItem() {
player?.replaceCurrentItem(with: _playerItem)
}
}
}
Edit 1: I've found one reason why the play is not happening when the app goes to background. I've the KVO which tells me when the player is ready to play by checking its status. Only when I receive the same I start
player.play()
But when the app is in background, it no longer receives this notification. Is there a way how I can get the notification even when the app is in background?
Edit 2: To clarify, app does play music if music starts at foreground. Problem is changing tracks in background is when KVO of player ready never gets triggered, unless I bring app to foreground.