源自其他一些帖子,我成功地为音乐播放器做好了一切。
最后一步是设置MPNowPlayingInfoCenter
值。
不幸的是,一旦我这样做,应用程序就会失去接收 remoteControlEvents 的能力,如果我位于设置属性的视图控制器之外的任何其他视图控制器中。将应用程序置于“音乐 VC”以外的任何其他 VC 的后台也是如此(它是一个选项卡式应用程序,音乐只是一个选项卡)
我的 AppDelegate:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
//here is other stuff for push-notifications etc.
UIApplication.sharedApplication().beginReceivingRemoteControlEvents()
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
return true
}
音乐VC:
class MusicVC:UIViewController, UITableViewDelegate,UITableViewDataSource,UICollectionViewDataSource, UICollectionViewDelegate {
var myPlayer:AVQueuePlayer!
override func viewDidLoad() {
super.viewDidLoad()
//tableView and other setup
self.becomeFirstResponder()
}
//MARK: - InfoCenter Methods
func setMediaCenterInfo() {
let mpic = MPNowPlayingInfoCenter.defaultCenter()
var albumArtWork = MPMediaItemArtwork(image: UIImage(named:"testImage"))
var fullString = self.currentSong.title as String
var splitArray = fullString.componentsSeparatedByString(" - ")
var artistName: String = splitArray[0]
var titleString: String? = splitArray.count > 1 ? splitArray[1] : nil
if titleString != nil {
mpic.nowPlayingInfo =
[
MPMediaItemPropertyArtwork:albumArtWork,
MPMediaItemPropertyTitle:titleString!,
MPMediaItemPropertyArtist:artistName
]
} else {
mpic.nowPlayingInfo =
[
MPMediaItemPropertyArtwork:albumArtWork,
MPMediaItemPropertyTitle:fullString
]
}
//Does get set correctly and shows in Info Center as well as Lock-Screen
}
override func canBecomeFirstResponder() -> Bool {
return true
}
override func remoteControlReceivedWithEvent(event: UIEvent) {
if event.type == UIEventType.RemoteControl {
switch event.subtype {
case .RemoteControlTogglePlayPause:
println("TOGGLE PLAY PAUSE")
//self.playToggleTapped(self)
case .RemoteControlPlay:
println("ONLY PLAY BUTTON")
//self.playToggleTapped(self)
case .RemoteControlPause:
println("ONLY PAUSE BUTTON")
//self.playToggleTapped(self)
case .RemoteControlNextTrack:
println("next")
//self.nexButtonTapped(self)
case .RemoteControlPreviousTrack:
//self.previousButtonTapped(self)
println("previous")
default:
break
}
}
}
}
显示另一个 VC 时,FirstResponder 会自动更改吗?感谢您提供解决此问题的提示。