swiftswiftuibluetoothwatchos

Trigger bluetooth headphone connection system screen on Apple Watch


I'm working on an app for the Apple Watch and I'm looking to implement functionality similar to what I've observed in the Spotify app.

Screenshot

Specifically, I'm interested in triggering the screen that prompts the user to connect Bluetooth headphones if none are connected when attempting to play audio.

I have attached a screenshot from the Spotify app which shows the exact screen I'm referring to. This screen appears when I try to play music without any Bluetooth headphones connected.

Here's a snippet of code I've attempted in my SwiftUI app, which simply plays a sound through the Apple Watch speaker but doesn't trigger the Bluetooth headphone connection screen:

struct ContentView: View {
    var audioPlayer = try! AVAudioPlayer(contentsOf: Bundle.main.url(forResource: "demo", withExtension: "mp3")!)

    var body: some View {
        Button("Play Sound") {
            playSound()
        }
    }

    func playSound() {
        do {
            let audioSession = AVAudioSession.sharedInstance()
            try audioSession.setCategory(.playback, mode: .default)
            try audioSession.setActive(true)
            
            audioPlayer.play()
        } catch {
            print("Error: \(error.localizedDescription)")
        }
    }
}

Could anyone guide me on how to invoke this screen? Is there a specific API or system call that can bring up this screen on the Apple Watch?

Any pointers or code samples would be greatly appreciated.


Solution

  • You need to enable background audio support and set your audio session appropriately.

    session.setCategory(AVAudioSession.Category.playback,
                            mode: .default,
                            policy: .longForm,
                            options: [])
    
    session.activate(options: []) { (success, error) in
        // Check for an error and play audio.
    }
    

    If necessary, the system will display a route picker promoting the user to select a Bluetooth audio route.

    For more information, refer to this Apple document