gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 05:41:33 26 4
gpt4 key购买 nike

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

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

关于ios - 如何检测股票音乐应用程序是否已终止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29481108/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com