Timer counting up in iOS Live Activity

1.3k Views Asked by At

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.

3

There are 3 best solutions below

1
On BEST ANSWER

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
)
5
On

Please check this answer I hope it will solve your problem

//
//  SampleStopWatch.swift
//

import UIKit

class SampleStopWatch:UIViewController {
    
    var timer:Timer?
    var startTime = Date()
   
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: (#selector(updateTimer)), userInfo: nil, repeats: true)
    }
    
    @objc func updateTimer() {
        let timeInterval =  Date().timeIntervalSince(startTime)
        let titleLabel = timeInterval.stringFromTimeInterval() // show this text on label
        //labeltoShow.text = titleLabel
        print("title label " + titleLabel)
    }
}
extension TimeInterval{
    
    func stringFromTimeInterval() -> String {
        
        let time = NSInteger(self)
        
        let ms = Int((self.truncatingRemainder(dividingBy: 1)) * 1000)
        let seconds = time % 60
        let minutes = (time / 60) % 60
        let hours = (time / 3600)
        
        return String(format: "%0.2d:%0.2d:%0.2d.%0.3d",hours,minutes,seconds,ms)
        
    }
}
0
On

If you want a timer that starts immediately after the live activity begins you can do this:

 Text(Date(timeIntervalSinceNow: Double(Date().timeIntervalSince(Date())) - Double(Date().timeIntervalSince(Date() - 1))
                        ),
                        style: .timer)