iOS Development

ios – How can I management the date format when deciding on .timer fashion in SwiftUI in ActivityKit

Spread the love

In my SwiftUI iOS 17 app, I’m displaying a timer in my ActivityWidget in order that the consumer can see a countdown timer when the cellphone display is locked.

In an effort to show the widget, I’m solely passing the tip Date to the Exercise Widget and utilizing the Textual content date fashion to show the timer countdown:

import ActivityKit
import WidgetKit
import SwiftUI

struct TimerAttributes: ActivityAttributes {
    let endDate: Date
    public struct ContentState: Codable, Hashable {

struct TimerWidgetLiveActivity: Widget {
    var physique: some WidgetConfiguration {
        ActivityConfiguration(for: TimerAttributes.self) { context in
            Textual content(context.attributes.endDate, fashion: .timer)
        } dynamicIsland: { context in
            DynamicIsland {
                DynamicIslandExpandedRegion(.main) {
                DynamicIslandExpandedRegion(.middle) {
                DynamicIslandExpandedRegion(.trailing) {
                DynamicIslandExpandedRegion(.backside) {
            } compactLeading: {
            } compactTrailing: {
            } minimal: {

The difficulty I’m having is with the inconsistent format of the textual content. What I would really like is for it to show like 03:32:44.

It does show like this when the display has simply been locked. However when the display goes to the all the time on state within the new iPhone it shows ‘3 hours, 32 minutes’.

I perceive dropping the seconds to save lots of battery however I would like 3:32:– which is what the native timer app does. Is there anyway to vary this formatting?

I’ve tried firing a timer and updating each second however that appears additionally like utilizing an excessive amount of battery and I desire dropping seconds when it goes to the all the time on state which it appears to handle effectively itself utilizing the Textual content styling.

Simply marvel what the most effective method is to point out timer with seconds if simply sleep and timer changing seconds with — within the all the time on state as a substitute of writing out ‘hours and minutes’ which takes an excessive amount of area and ruins the restricted UI.

Leave a Reply

Your email address will not be published. Required fields are marked *