3

I need to build an iOS Swift single-page app which has a countdown timer for 60:00 minutes. After 2 seconds I need to show a UILabel, hide it after 6 seconds and then show another text after that. This is my code so far for the timer:

var startTime = NSTimeInterval()
var timer = NSTimer()

func startCountdownTimer() {

    var currentTime = NSDate.timeIntervalSinceReferenceDate()

    //Find the difference between current time and start time.
    var elapsedTime: NSTimeInterval = 3600-(currentTime-startTime)

    //Calculate the minutes in elapsed time.
    let minutes = UInt8(elapsedTime / 60.0)
    elapsedTime -= (NSTimeInterval(minutes) * 60)

    //Calculate the seconds in elapsed time.
    var seconds = UInt8(elapsedTime)
    elapsedTime -= NSTimeInterval(seconds)

    //Add the leading zero for minutes and seconds and store them as string constants
    let strMinutes = minutes > 9 ? String(minutes):"0" + String(minutes)
    let strSeconds = seconds > 9 ? String(seconds):"0" + String(seconds)

    //Concatenate minutes and seconds and assign it to the UILabel
    timerLabel.text = "\(strMinutes):\(strSeconds)"

}

I've tried doing something like this:

if elapsedTime == 2 {
    introTextLabel.hidden = false
}

or this:

if (elapsedTime: NSTimeInterval(seconds)) == 2 {
    introTextLabel.hidden = false
}

But it doesn't work. Can anyone help?

introTextLabel - Label to show text in

timerLabel - Label for timer

Cesare
  • 8,326
  • 14
  • 64
  • 116
MarkoDeveloper
  • 267
  • 1
  • 3
  • 11

1 Answers1

9

You can use this useful delay() function written by matt.

func delay(delay:Double, closure:()->()) {
    dispatch_after(
        dispatch_time(
            DISPATCH_TIME_NOW,
            Int64(delay * Double(NSEC_PER_SEC))
        ),
    dispatch_get_main_queue(), closure)
}

Usage:

// Wait two seconds:
delay(2.0) {
    print("Hello!")
}
Community
  • 1
  • 1
Cesare
  • 8,326
  • 14
  • 64
  • 116