Dario Raffa
Dario Raffa

Reputation: 57

iOS Live Activity timer with automatic update

i need to create timer-like with live activities. I noticed that system clock app can start live activity when timer is started. In addition, value inside change every second.

In official Apple documentation only ways to update live activities are Attributes struct or push notification. I asked to me if timer send push notification every second but i think this is impossible.

I try to use ProgressView or TimelineView inside live activity but anything change.

Anyone can help me?

This is an example of my expectation image

Upvotes: 4

Views: 1567

Answers (1)

NSPratik
NSPratik

Reputation: 4858

Text and ProgressView are system UI components that support auto-updating a live activity.

These are built-in APIs which update specific parts of a live notification, such as ProgressView(timerInterval:countsDown:label:currentValueLabel:), which updates a progress view in your live activity every second or Text(timerInterval:pauseTime:countsDown:showsHours:), which updates a Text displaying a count down every second. These APIs keep updating your live activity even if the app has been killed by either the system or the user.

However, these APIs are quite limited in what they can do and aren't customisable at all, so if you want to update some custom UI or change the update frequency, these APIs.

Take ClosedRange type inside ActivityAttributes

struct ParkWidgetAttributes: ActivityAttributes {
    
    var startDate: Date
    var endDate: Date

    // 'ContentState' represents the dynamic content of the Live Activity.
    public struct ContentState: Codable, Hashable {
        // Dynamic stateful properties about your activity go here!
        var parkingTimer: ClosedRange<Date>
    }
}

Use that attribute inside View

struct LockScreenParkLiveActivityView: View {
    
    let context: ActivityViewContext<ParkWidgetAttributes>

    var body: some View {

        Text(
            timerInterval: context.state.parkingTimer, 
            countsDown: true
        )
        .monospacedDigit()
        .font(.system(size: 32, weight: .bold))
        .padding(.leading, 3)

        ProgressView(
            timerInterval: context.state.parkingTimer,
            countsDown: false
        )
        .padding(.horizontal, 3)
        .padding(.bottom, 5)
        .tint(.blue)
    }
}

Upvotes: 1

Related Questions