我试图在 SwiftUI 2.0 应用程序中单击蓝牙耳机按钮来简单地执行代码,但是在尝试了许多不同的代码之后,没有任何效果......有人解决了这个问题吗?
基于苹果文档和我在 StackOverflow ( https://stackoverflow.com/a/58249502/13207818 ) 上找到的一些答案,我尝试了这个简单的代码
import SwiftUI
import MediaPlayer
struct ContentView: View {
init() {
MPRemoteCommandCenter.shared().pauseCommand.isEnabled = true
MPRemoteCommandCenter.shared().pauseCommand.addTarget(handler: { (event) in
print("Pause")
return MPRemoteCommandHandlerStatus.success
})
MPRemoteCommandCenter.shared().playCommand.isEnabled = true
MPRemoteCommandCenter.shared().playCommand.addTarget(handler: { (event) in
print("Play")
return MPRemoteCommandHandlerStatus.success
})
MPRemoteCommandCenter.shared().togglePlayPauseCommand.addTarget (handler: { (event: MPRemoteCommandEvent) -> MPRemoteCommandHandlerStatus in
// middle button (toggle/pause) is clicked
print("event:", event.command)
return .success
})
}
var body: some View {
Text("Hello World")
}
}
当然根据Apple doc启用背景音频
<key>UIBackgroundModes</key>
<array>
<string>audio</string>
</array>
甚至尝试激活我的应用音频会话:
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playAndRecord, mode: .default, options: [.duckOthers, .allowBluetooth, .allowBluetoothA2DP])
try AVAudioSession.sharedInstance().setActive(true, options: .notifyOthersOnDeactivation)
print("audioSession is Active")
} catch {
print("audioSession properties weren't set because of an error.")
print(error)
}
但一切都失败了……
有人会知道我做错了什么,还是会遇到 swiftUI 2.0 的此类问题?
预先感谢您的支持