Reputation: 946
I want to see that my program knows when the timer is done. I'm using WKInterfaceTimer in Xcode 7 Beta 3 (7A152u). The "Tick Tock" prints to the console while the counter is counting down. But when it reaches 0, "Timer Done" does not print.
@IBOutlet var myTimer: WKInterfaceTimer!
@IBAction func startButton() {
myTimer.start()
myTimer.setDate(NSDate(timeIntervalSinceNow: 4)) // Arbitrary 4 second coundown.
// Impliment an alert.
if myTimer == 0 {
print("Timer Done")
} else {
print("Tick Tock")
}
}
Upvotes: 1
Views: 470
Reputation: 946
This is the solution I came up with. Right now the alert at the end of the timer simply prints to the console with "Done". Big thanks to user Prawn as I used some of his code in this solution.
import WatchKit
import Foundation
var myTimer : NSTimer?
var elapsedTime : NSTimeInterval = 0.0
var startTime = NSDate()
var duration : NSTimeInterval = 4.0 //Arbitrary 4 seconds to test timer.
class InterfaceController: WKInterfaceController {
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
WKTimer.setDate(NSDate(timeIntervalSinceNow: duration))
}
override func willActivate() {
super.willActivate()
}
@IBOutlet var WKTimer: WKInterfaceTimer! //The WatchKit timer the user sees
@IBAction func startButton() { //Start button
NSTimer.scheduledTimerWithTimeInterval(duration, target: self, selector: ("timerDone"), userInfo: nil, repeats: false)
WKTimer.setDate(NSDate(timeIntervalSinceNow: duration ))
WKTimer.start()
}
//Reset button resets the timer back to the original time set.
@IBAction func resetButton() {
WKTimer.stop()
WKTimer.setDate(NSDate(timeIntervalSinceNow: duration))
}
func timerDone() {
print("Done")
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
}
Upvotes: 1
Reputation: 4235
What you did is wrong. After you call setDate
the timer start counting down. To get info what is actual state of the timer you should instantiate NSTimer
and check when it fires.
From Apple's Documentation:
To know when the timer reaches 0, configure an NSTimer object with the same target date you used to set up the timer.
Upvotes: 0