我创建了一个音乐应用程序,现在我想添加一个功能来从锁定屏幕和控制中心控制音乐,但我收到错误消息,MPRemoteCommandCenter 不在范围内。
这是我的代码的外观。
我正在 XCode 12 中开发,但适用于 iOS 12.4。
import UIKit
import AVKit
class SongViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(respondToSwipeGesture))
swipeRight.direction = .right
self.view.addGestureRecognizer(swipeRight)
let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(respondToSwipeGesture))
swipeLeft.direction = .left
self.view.addGestureRecognizer(swipeLeft)
setupRemoteTransportControls()
setupNowPlaying()
}
func setupRemoteTransportControls() {
let commandCenter = MPRemoteCommandCenter.shared()
commandCenter.playCommand.addTarget { [unowned self] event in
print("Play command - is playing: \(self.player.isPlaying)")
if !self.player.isPlaying {
self.play()
return .success
}
return .commandFailed
}
// Add handler for Pause Command
commandCenter.pauseCommand.addTarget { [unowned self] event in
print("Pause command - is playing: \(self.player.isPlaying)")
if self.player.isPlaying {
self.pause()
return .success
}
return .commandFailed
}
}