Can't catch bluetooth headset button click event in swiftui 2.0

318 Views Asked by At

I am trying to simply execute code on a click of a bluetooth headset button in a SwiftUI 2.0 app, but after trying many different codes, nothing have worked... Does someone have solved this issue?

Based on apple docs and some answer I found on StackOverflow (https://stackoverflow.com/a/58249502/13207818), I tried this simple code

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")
    }
}

Of course Enabling Background Audio as per Apple doc

<key>UIBackgroundModes</key>
    <array>
        <string>audio</string>
    </array>

Even tried to activate my app audio session:

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)
        }

But everything failed...

Would someone know what I am doing wrong or would have faced such issue with swiftUI 2.0?

Thank in advance for your support

2

There are 2 best solutions below

1
On

In general you shouldn’t do actions in the initializers of views. Since they represent the state of the UI, not the actual UI they could be broken down and created again whenever SwiftUI thinks it needs to.

Im not at my pc but You can probably get a Publisher for the pause button which you can bind to a view with onReceive

0
On

Finally, I got a solution for my issue. I don't know how it works really behind but the audio focus wasn't on my app. So I've just played a silent sound for a second and I could play properly with my play/pause button. I know that it's not a proper solution, but it works! This reminds me of a similar bug on the galaxy s8... If I find a better one, I'll keep you posted.