Lilbit

Learn a little bit every day

swift6.2swiftui

SwiftUI 6.2: Smart Live Activity Updates with State-Driven Content Management

Daily tips and best practices

Tip
Use @State with ActivityKit's live activities to automatically sync UI updates with background state changes. Add .task(id: activityState) modifier to your Live Activity widget to trigger content updates when your state identifier changes, ensuring real-time synchronization without manual refresh calls.
Best Practice: Implement Type-Safe Live Activity State Management

This pattern creates a robust Live Activity system by using a computed `stateIdentifier` that combines multiple state properties, ensuring UI updates trigger whenever any critical data changes. The `.task(id:)` modifier provides automatic lifecycle management for async operations tied to state changes.

import ActivityKit
import SwiftUI

struct DeliveryTracker: ActivityAttributes {
    public struct ContentState: Codable, Hashable {
        var status: DeliveryStatus
        var estimatedArrival: Date
        var driverLocation: String
        
        var stateIdentifier: String {
            "\(status.rawValue)-\(estimatedArrival.timeIntervalSince1970)"
        }
    }
    
    var orderID: String
    var customerName: String
}

struct LiveDeliveryView: View {
    let context: ActivityViewContext<DeliveryTracker>
    @State private var refreshTrigger = 0
    
    var body: some View {
        HStack {
            VStack(alignment: .leading) {
                Text("Order #\(context.attributes.orderID)")
                    .font(.headline)
                Text(context.state.status.displayName)
                    .foregroundStyle(context.state.status.color)
                Text("ETA: \(context.state.estimatedArrival, format: .dateTime.hour().minute())")
                    .font(.caption)
            }
            Spacer()
            Image(systemName: context.state.status.icon)
                .foregroundStyle(context.state.status.color)
        }
        .task(id: context.state.stateIdentifier) {
            refreshTrigger += 1
        }
    }
}

Why This is a Best Practice

Live Activities require precise state synchronization to provide accurate real-time information. By creating a unique identifier that encompasses all relevant state data and using SwiftUI's built-in task lifecycle management, we ensure updates happen reliably while avoiding unnecessary recomputation and maintaining optimal battery performance through efficient change detection.

History

Loading...