iosswiftswiftuiwidgetliveactivity

Timer counting up in iOS Live Activity


I'm wondering if it's possible to create a simple seconds counter that is counting up in iOS Live Activities that would start from the provided unix timestamp and be relative to current date. For example: '00:01', '00:02', ...

I know how to create a countdown timer, like so:

Text(Date(timeIntervalSinceNow: 60), style: .timer)

But I haven't been successful in getting it to work the other way around, or finding much relevant information regarding this.


Solution

  • This is the solution I ended up going with. I noticed that the timer will start counting up when the passed in time interval is negative value. [context.state.startedAt] is unix timestamp in seconds.

    Text(
      Date(
        timeIntervalSinceNow: Double(context.state.startedAt) - Date().timeIntervalSince1970
      ),
      style: .timer
    )