简体   繁体   中英

Making a Legit Countdown Timer in 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.

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)

The items you are missing or need correction are written below:

var startTime: NSDate = NSDate()
var endTime: NSDate?

func viewDidLoad() {
    let clock = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "countdown", userInfo: nil, repeats: true)
    endTime = startTime.dateByAddingTimeInterval(21600)
}

func countdown() {
    printSecondsToHoursMinutesSeconds(Int(timeLeft()))
}

func timeLeft() -> Double {
    return endTime!.timeIntervalSinceNow
}

To measure the time when the app is not running requires saving the time when the app goes into the background and then comparing the saved time when the app is opened again. The time can be saved as an NSDate . A comparison between two NSDates can give you an NSTimeInterval , the number of elapsed seconds between the two dates. For example:

let remainingTime = savedTime.timeIntervalSinceNow

See applicationDidBecomeActive: and applicationDidEnterBackground: in your app delegate for the place to compare and save the date into NSUserDefaults.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM