[英]How can I detect if the stock music app has been terminated?
我正在使用MPMusicPlayerController.systemMusicPlayer()
制作音乐播放器来学习Swift,除了一个小问题,一切都进行得很好。 每当从我的应用程序播放音乐时,然后我切换到音乐应用程序并通过多任务终止它,则音乐会按预期停止,但是当我切换到该应用程序时,我的应用程序会崩溃。 我以为这可能是由于我没有为音乐终止时应设置的条件设置条件,而且我似乎在Apple Docs中找不到任何真正有用的条件。 我试过了
if (musicPlayer.playbackState == MPMusicPlaybackState.Interrupted) || (musicPlayer.playbackState == MPMusicPlaybackState.Stopped)
无济于事。 任何人都可以提供一些有关为什么发生这种情况和/或解决方案的见解吗? 这是我的代码示例:
override func viewDidLoad() {
super.viewDidLoad()
var notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.addObserver(self, selector: "handlePlayingItemChanged", name: MPMusicPlayerControllerNowPlayingItemDidChangeNotification, object: musicPlayer)
notificationCenter.addObserver(self, selector: "handlePlayState", name: MPMusicPlayerControllerPlaybackStateDidChangeNotification, object: musicPlayer)
musicPlayer.beginGeneratingPlaybackNotifications()
if (musicPlayer.playbackState == MPMusicPlaybackState.Playing) {
playButton.setImage(pause, forState: UIControlState.Normal)
setupCurrentMediaItem()
handleShuffleAndReplayMode()
self.isPlay = true
} else if (musicPlayer.playbackState == MPMusicPlaybackState.Paused) {
playButton.setImage(play, forState: UIControlState.Normal)
self.isPlay = false
} else if (musicPlayer.playbackState == MPMusicPlaybackState.Interrupted) || (musicPlayer.playbackState == MPMusicPlaybackState.Stopped) {
playButton.setImage(play, forState: UIControlState.Normal)
self.isPlay = false
}
}
如果不删除观察者,则总是会引发异常:
您添加了无条件观察者以将其删除:
notificationCenter.addObserver...
删除观察者:
notificationCenter.removeObserver...
在此处查找更多信息- 键值观察编程指南
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.