iosswiftdelegatesviewcontrollermpnowplayinginfocenter

How can I get access to ViewController from MPNowPlayingInfoCenter


I'm working on an audio player and came across this situation: I have a TrackDetailView that opens to play a track when I click on a TableView cell. Also I have implemented background playback and MPNowPlayingInfoCenter. When I press Pause or Play button in MPNowPlayingInfoCenter, I want the button image to change on my TrackDetailView as well, but I just can't do it. I will be glad for any help. Important note(!) TrackDetailView and MPNowPlayingInfoCenter are in different classes. When I put them in one class everything works without problems. My code:

class TrackDetailView: UIView {
   var audioPlayer = AudioPlayer()
   ...
   @IBOutlet var playPauseButton: UIButton!
   ...
   //Loading with view
   func set() {
   setupMediaPlayerNotificationView()
   }
}

class AudioPlayer {
var trackDetailView: TrackDetailView?
func setupMediaPlayerNotificationView() {
        let commandCenter = MPRemoteCommandCenter.shared()
        
        commandCenter.playCommand.addTarget { [unowned self] event in
            if self.player.rate == 0.0 {
                self.player.play()
                self.trackDetailView?.playPauseButton.setImage(#imageLiteral(resourceName: "pause"), for: .normal)
            }
            return .commandFailed
        }
        
        commandCenter.pauseCommand.addTarget { [unowned self] event in
            if self.player.rate == 1.0 {
                self.player.pause()
                self.trackDetailView?.playPauseButton.setImage(#imageLiteral(resourceName: "play"), for: .normal)
                return .success
            }
            return .commandFailed
        }
       ...
    }
}

I think I have a problem with an instance of the TrackDetailView class.


Solution

  • You need to make sure that for this instance

    var audioPlayer = AudioPlayer()
    

    you set

    audioPlayer.trackDetailView = self
    

    e.x here

    func set() {
      audioPlayer.trackDetailView = self
      audioPlayer.setupMediaPlayerNotificationView()
    }