我创建了一个类来处理远程控制事件的设置。所有的print语句都在函数的主体中打印,但是事件永远不会被调用。同样,元数据也永远不会显示在锁定屏幕或命令中心上。我叫UIApplication.shared.beginReceivingRemoteControlEvents()
在应用程序委托didFinishLaunching中。有人可以解释为什么没有显示数据以及为什么控件不起作用吗?音频会话也设置为.playback
RemoteControlsHelper类{
static let instance = RemoteControlsHelper()
var currentPodcast = Podcast()
var player = AVAudioPlayer()
func setupRemoteTransportControls() {
// Get the shared MPRemoteCommandCenter
print("setting up commands")
let commandCenter = MPRemoteCommandCenter.shared()
commandCenter.playCommand.isEnabled = true
commandCenter.pauseCommand.isEnabled = true
// Add handler for Play Command
commandCenter.playCommand.addTarget { (event) -> MPRemoteCommandHandlerStatus in
if self.player.rate == 0.0 {
self.player.play()
print("s")
return .success
}
print("f")
return .commandFailed
}
// Add handler for Pause Command
commandCenter.pauseCommand.addTarget { (event) -> MPRemoteCommandHandlerStatus in
if self.player.rate == 1.0 {
self.player.pause()
print("s")
return .success
}
print("f")
return .commandFailed
}
}
func setupNowPlaying(img: UIImage?) {
print("setting data")
// Define Now Playing Info
var nowPlayingInfo = [String : Any]()
nowPlayingInfo[MPMediaItemPropertyTitle] = self.currentPodcast.title
nowPlayingInfo[MPMediaItemPropertyArtist] = self.currentPodcast.author
print(self.currentPodcast.title)
if let image = img {
nowPlayingInfo[MPMediaItemPropertyArtwork] =
MPMediaItemArtwork(boundsSize: image.size) { size in
return image
}
}
print("continuing")
//nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = self.player.currentTime
//nowPlayingInfo[MPMediaItemPropertyPlaybackDuration] = self.player.duration
//nowPlayingInfo[MPNowPlayingInfoPropertyPlaybackRate] = self.player.rate
// Set the metadata
MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo
}
@objc func toggleAudio() {
if self.player.isPlaying {
self.player.pause()
} else {
self.player.play()
}
}
}