如何从 MPNowPlayingInfoCenter 访问 ViewController

How can I get access to ViewController from MPNowPlayingInfoCenter

我正在开发音频播放器并遇到了这种情况: 当我单击 TableView 单元格时,我有一个 TrackDetailView 打开以播放曲目。我还实现了后台播放和 MPNowPlayingInfoCenter。 当我在 MPNowPlayingInfoCenter 中按下暂停或播放按钮时,我希望按钮图像在我的 TrackDetailView 上也发生变化,但我做不到。我很乐意提供任何帮助。 重要说明 (!) TrackDetailView 和 MPNowPlayingInfoCenter 在不同的 classes 中。当我将它们放在一个 class 中时,一切正常。 我的代码:

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
        }
       ...
    }
}

我想我的 TrackDetailView 实例有问题 class。

您需要确保对于此实例

var audioPlayer = AudioPlayer()

你设置

audioPlayer.trackDetailView = self

e.x这里

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