簡體   English   中英

如何檢測股票音樂應用程序是否已終止?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM