Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a button in live activity?How can not allow open app when click this button?

Tags:

xcode

ios

swiftui

How to create a button in live activity?How can not allow open app when click this button?enter image description here

like image 847
Z.H Q Avatar asked Sep 03 '25 06:09

Z.H Q


1 Answers

May 2024 Update

Now you can in iOS 17! Full documentation here.

Starting with iOS 17, iPadOS 17, or macOS 14, widgets and Live Activities can include buttons and toggles to offer specific app functionality without launching the app

For example, a Reminders widget allows people to mark a task as completed with a toggle. On a locked device, buttons and toggles are inactive and the system doesn’t perform actions unless a person authenticates and unlocks their device.

Add the functionality as an intent

  1. For a widget, create a new structure that adopts the AppIntent protocol and add it to your app target. For a Live Activity interactive, adopt the LiveActivityIntent protocol
  2. Implement the protocol’s requirements.
  3. Define input parameters that your action needs using the @Parameter property wrapper (must conform to AppEntity)
  4. In the protocol’s required perform() function, add code for the action you want to make available to the widget.

Example:

@available(iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0, *)
struct SuperCharge: LiveActivityIntent {
    
    static var title: LocalizedStringResource = "Emoji Ranger SuperCharger"
    static var description = IntentDescription("All heroes get instant 100% health.")
    
    func perform() async throws -> some IntentResult {
        EmojiRanger.superchargeHeros()
        return .result()
    }
}

Notes

  • The perform() function is asynchronous.
  • When you return from the perform() function, the system reloads the widget’s timeline using its timeline provider.
  • The perform() function is marked as throws.

Add the button

struct EmojiRangerWidgetEntryView: View {
    var entry: SimpleEntry
    
    @Environment(\.widgetFamily) var family
    
    @ViewBuilder
    var body: some View {
        switch family {
        
        // Code for other widget sizes.
           
        case .systemLarge:
            if #available(iOS 17.0, *) {
                HStack(alignment: .top) {
                    Button(intent: SuperCharge()) {
                        Image(systemName: "bolt.fill")
                    }
                }
                .tint(.white)
                .padding()
            }
            // ...rest of view
       }
    }
}
like image 149
Kyle Venn Avatar answered Sep 04 '25 21:09

Kyle Venn