Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a Legit Countdown Timer in SWIFT

Tags:

xcode

ios

swift

I'm trying to get a label to countdown when a button is pressed, showing the countdown in a (hr,min,sec) way. I've kind of tried to connect two different codes I found. Here's what I have:

*updated code (some psuedo code)*

var timer = NSTimer()

func timerResults() {
    let theDate = NSDate()
    var endTime = theDate //+ 6 hours
    let timeLeft = endTime - theDate
    timeLeftLabel.text = "\(timeLeft)"
}


@IBOutlet weak var timeLeftLabel: UILabel!

@IBAction func IBbtnUpdateTap(sender: UIButton){

        timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("timerResults"), userInfo: nil, repeats: true)

    }

Also, how do I make this counting down actively happen even when the app isn't running? Essentially, I'm creating a reward system if the user comes back in 6 hours.

like image 894
adman Avatar asked Apr 24 '26 22:04

adman


1 Answers

I can't give a long answer right now but the easiest way is as follows:

When the user starts the timer with some amount of seconds, calculate the exact date when the timer should end (end time = now + amount of seconds). Now you can update the label every display refresh with the calculated time remaining (time left = end time - now).

This way it's guaranteed to keep the time on app relaunches (of course you need to save the ending date with NSUserDefaults or something) and it also guarantees no fluctuations in timer speed (NSTimer wouldn't guarantee that)

like image 74
Kametrixom Avatar answered Apr 27 '26 12:04

Kametrixom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!