MusicPlayerからの通知に対応
動作を確認した環境
環境 | 情報 |
---|---|
Xcode | 6.3.2 (6D2105) |
iOS | 8.3 |
Swift | 1.2 |
Date | 2015/6/5 |
MusicPlayerからの通知に対応
再生している状態や曲の変化は、MPMusicPlayerControllerからNSNotificationCenterを通して通知されるので、これに対応する。
具体的にはこんな感じ。変更点だけ抜粋。
class SK4MusicPlayerAdmin: NSObject { //////////////////////////////////////////////////////////////// // MARK: - 初期化&プロパティ /// アプリ全体で使用するMPMusicPlayerController let player = MPMusicPlayerController.systemMusicPlayer() override init() { super.init() registAllObserver() } deinit { removeAllObserver() } //////////////////////////////////////////////////////////////// // MARK: - 通知 func registAllObserver() { let nc = NSNotificationCenter.defaultCenter() nc.addObserver(self, selector: "didEnterBackground:", name: UIApplicationDidEnterBackgroundNotification, object: nil) nc.addObserver(self, selector: "willEnterForeground:", name: UIApplicationWillEnterForegroundNotification, object: nil) nc.addObserver(self, selector: "playItemChanged:", name: MPMusicPlayerControllerNowPlayingItemDidChangeNotification, object: player) nc.addObserver(self, selector: "playbackStateChanged:", name: MPMusicPlayerControllerPlaybackStateDidChangeNotification, object: player) player.beginGeneratingPlaybackNotifications() } func removeAllObserver() { player.endGeneratingPlaybackNotifications() let nc = NSNotificationCenter.defaultCenter() nc.removeObserver(self, name: UIApplicationDidEnterBackgroundNotification, object: nil) nc.removeObserver(self, name: UIApplicationWillEnterForegroundNotification, object: nil) nc.removeObserver(self, name: MPMusicPlayerControllerNowPlayingItemDidChangeNotification, object: player) nc.removeObserver(self, name: MPMusicPlayerControllerPlaybackStateDidChangeNotification, object: player) } //////////////////////////////////////////////////////////////// func didEnterBackground(notify: NSNotification) { onDidEnterBackground() } func willEnterForeground(notify: NSNotification) { onWillEnterForeground() } func playItemChanged(notify: NSNotification) { onPlayItemChanged() } func playbackStateChanged(notify: NSNotification) { onPlaybackStateChanged() } //////////////////////////////////////////////////////////////// // MARK: - イベント対応 /// アプリがバックグラウンドになった func onDidEnterBackground() { println(__FUNCTION__) } /// アプリがフォアグラウンドになる func onWillEnterForeground() { println(__FUNCTION__) } /// アイテムが変更になった func onPlayItemChanged() { println(__FUNCTION__) } /// 再生状況が変化した func onPlaybackStateChanged() { println(__FUNCTION__) } 以下略
この辺りの処理は決まりきったことをやるだけ。どうせあとで必要になるので、MusicPlayerのついでにBackground/Foregroundの通知も設定してる。イベント処理として、通知を受けた後に別に一段いれてあるのは、あとで処理を切り分けるため・・・ というより好みの問題かも。
ソースコードの全体はこちら。
See_Ku / MusicPlayerTips — Bitbucket
https://bitbucket.org/See_Ku/musicplayertips