我的应用程序可以选择允许其声音与其他应用程序混合。根据 Apple 的说法,MPRemoteCommandCenter 仅在应用程序不允许混合时可用。
在我的应用程序中,当用户点击按钮更改 mixWithOthers 设置时,音频会话会相应设置。
但是,即使用户切换回不允许再混合,MPRemoteCommandCenter 也不会显示在锁定屏幕中,直到应用程序从缓存中删除(向上滑动)并重新启动。
有没有办法实现所需的行为而无需重新启动应用程序?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
UIApplication.shared.beginReceivingRemoteControlEvents()
}
var isMixWithOthersAllowed: Bool
func startProcess() {
setAudioSession {
setupMediaControls()
}
}
func setAudioSession(completion: @escaping () -> Void) {
let audioSession = AVAudioSession.sharedInstance()
do {
if isMixWithOthersAllowed {
try audioSession.setCategory(.playback, options: [.mixWithOthers])
/* The remote command center will not be available when mixing with others,
as stated by Apple in the docs. */
} else {
try audioSession.setCategory(.playback)
/* The remote command center should be available when switching back to
this category, but it will only show up after the app has been killed
and started fresh again. I'd like it to be available without restarting
the application. */
}
try audioSession.setActive(true)
} catch let error as NSError {
configureAudioSessionError = error
}
assert(configureAudioSessionError == nil, "Create audio session failed")
completion()
}
func setupMediaControls() {
let commandCenter = MPRemoteCommandCenter.shared()
commandCenter.playCommand.isEnabled = true
commandCenter.pauseCommand.isEnabled = true
commandCenter.nextTrackCommand.isEnabled = true
commandCenter.previousTrackCommand.isEnabled = true
// Setup handlers for commands
// ...
setupNowPlaying()
}
func setupNowPlaying() {
// Configure audio track metadata and update UI elements
}