Zifigo
Zifigo

Reputation: 206

Reading the physical action button on Apple Watch Ultra

I downloaded and tested the example you can find here: https://github.com/KhaosT/WatchActionButtonExample

It works fine in terms of creating the intents so your app can be linked to the physical button in WatchOS settings. I can add "print" sentences and see that the app catches all subsequent action button pushes. All good and fine.

But it doesn't really show how to link the intent to some action in the User Interface.

So my question is what kind of code to add to the perform() func in StartWorkoutIntent, so I can make some action in the User interface.

If the watchApp isn't running, I suppose it's not yet loaded when the StartWorkoutIntent is caught, so how do I get the information to the watchApp, that it was started from an Intent and should start the workout instead of waiting for user input?

This example is also based on the same example code above, but also just conviently writes "// Start your workout here" in the perform() func. https://crunchybagel.com/adding-support-for-apple-watch-ultra-action-button/

Upvotes: 0

Views: 304

Answers (1)

Zifigo
Zifigo

Reputation: 206

I found that by using a singleton class, I can share data between the StartWorkoutIntent and my SwiftUI View.

Simplified it could look like this

class IntentCommunication : ObservableObject {
    static let shared = IntentCommunication()
    @Published var buttonPushed = false
    
    private init(){
        print("Initializing IntentCommunication")
        buttonPushed = false
    }
}

In the perform func in StartWorkoutIntent I can set my var like this:

@MainActor
func perform() async throws -> some IntentResult {
    IntentCommunication.shared.buttonPushed = true
    
    return .result(actionButtonIntent: PauseIntent())
}

and in my View I'll have this

struct LaunchView: View {
    @StateObject var intentCommunication = IntentCommunication.shared

and can for instance use the shared variable in a .onChanged or .onAppear statement.

Upvotes: 2

Related Questions