1

I'm a beginner in Swift and I'm facing a problem.

I want to create a class that contains a timer and a button Everytime the button is tapped I have to restart the timer, if the time elapsed between the timer starts and the button is tapped is greater (or equal) to 400 milliseconds, I have to call the function in the selector.

But there isn't a "GetTimeElapsed()" method in swift and I don't know how to do it. If you have some clue/tutorials it could be cool !

Thx guys

Alexandre Odet
  • 75
  • 1
  • 1
  • 8

2 Answers2

1

Few small steps:

  1. Define the start time: (should happen at the same time you start the timer)

    startTime = (NSDate.timeIntervalSinceReferenceDate())

  2. Measure the time difference

    let elapsed = NSDate.timeIntervalSinceReferenceDate() - startTime

Idan
  • 5,405
  • 7
  • 35
  • 52
0

By default, NSTimer does not have this feature.
Right way is do your job with dates and comparing it.

By the way, you can do a nice extension like this:

public extension NSTimer {
    var elapsedTime: NSTimeInterval? {
        if let startDate = self.userInfo as? NSDate {
           return NSDate().timeIntervalSinceDate(startDate)
        }
        return nil 
    }
}

In this way, when you create your timer, you have to set userInfo:

let timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(foo), userInfo: NSDate(), repeats: true)

In your 'foo' method you can test elapsed time:

func foo() {
   print(self.timer.elapsedTime)
}
narner
  • 2,908
  • 3
  • 26
  • 63
Luca Davanzo
  • 21,000
  • 15
  • 120
  • 146