简体   繁体   中英

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; 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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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