0

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.

VyacheslavB
  • 181
  • 9

1 Answers1

1

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()
}
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
  • Thank you very much! It really works! Can you explain this in more detail? Why was it needed? – VyacheslavB Aug 01 '20 at 12:33
  • 1
    shortly this `var trackDetailView: TrackDetailView?` is nil until you link it by assignment to an existing shown view otherwise nothing will work upon doing `trackDetailView?.......` so `audioPlayer.trackDetailView = self` comes to rescue – Shehata Gamal Aug 01 '20 at 12:35