skip to Main Content

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.

2

Answers


  1. 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)
            
        }
    }
    
    Login or Signup to reply.
  2. As far as I know, there is nothing out of the box, you need to set this up yourself. So
    you could try something simple like using a Timer and two vars:

    struct ContentView: View {
        @State var secs = 0
        @State var mins = 0
        let timer = Timer.publish(every: 1, tolerance: 0.5, on: .main, in: .common).autoconnect()
        
        var body: some View {
            Text("(mins):(secs)")
                .onReceive(timer) { _ in
                    if (secs == 59) {
                        secs = 0
                        mins += 1
                    } else {
                        secs += 1
                    }
                }
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search