在范围内找不到 MPRemoteCommandCenter
Can not find MPRemoteCommandCenter in scope
我已经创建了一个音乐应用程序,现在我想添加一个功能来从锁定屏幕和控制中心控制音乐,但我收到错误消息,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
}
}
您需要导入 MediaPlayer
框架
import UIKit
import AVKit
import MediaPlayer
...
我已经创建了一个音乐应用程序,现在我想添加一个功能来从锁定屏幕和控制中心控制音乐,但我收到错误消息,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
}
}
您需要导入 MediaPlayer
框架
import UIKit
import AVKit
import MediaPlayer
...