简体   繁体   English

如何检测股票音乐应用程序是否已终止?

[英]How can I detect if the stock music app has been terminated?

I'm making a music player using MPMusicPlayerController.systemMusicPlayer() to learn Swift and everything is going pretty well except for one small problem; 我正在使用MPMusicPlayerController.systemMusicPlayer()制作音乐播放器来学习Swift,除了一个小问题,一切都进行得很好。 whenever music is playing from my app, and then I switch over to the music app and terminate it via multitasking, the music stops as expected but my app crashes when I switch to it. 每当从我的应用程序播放音乐时,然后我切换到音乐应用程序并通过多任务终止它,则音乐会按预期停止,但是当我切换到该应用程序时,我的应用程序会崩溃。 I was thinking this might be due to the fact that I have not set a condition for what should happen when music is terminated and I can't seem to find anything in the Apple Docs that actually helps. 我以为这可能是由于我没有为音乐终止时应设置的条件设置条件,而且我似乎在Apple Docs中找不到任何真正有用的条件。 I tried 我试过了

if (musicPlayer.playbackState == MPMusicPlaybackState.Interrupted) || (musicPlayer.playbackState == MPMusicPlaybackState.Stopped)

to no avail. 无济于事。 Can anyone offer some insight as to why this is happening and/or a solution? 任何人都可以提供一些有关为什么发生这种情况和/或解决方案的见解吗? Here's a sample of my code: 这是我的代码示例:

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
        }
    }

If you do not remove the observers you will always throw an exception: 如果不删除观察者,则总是会引发异常:

You added observers without condition to remove them: 您添加了无条件观察者以将其删除:

notificationCenter.addObserver...

Remove Observers: 删除观察者:

notificationCenter.removeObserver...

Look here for more info - Key-Value Observing Programming Guide 在此处查找更多信息- 键值观察编程指南

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM