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

时间:2015-04-06 23:03:41

标签: ios swift mpmusicplayercontroller

我正在使用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
        }
    }

1 个答案:

答案 0 :(得分:0)

如果你不删除观察者,你将总是抛出异常:

您添加了无条件的观察者以删除它们:

notificationCenter.addObserver...

删除观察员:

notificationCenter.removeObserver...

在这里查看更多信息 - Key-Value Observing Programming Guide