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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With