当 WKInterfaceTimer 达到 0 时打印到控制台

Print to Console when WKInterfaceTimer reaches 0

我想看到我的程序知道计时器何时结束。我在 Xcode 7 Beta 3 (7A152u) 中使用 WKInterfaceTimer。 "Tick Tock" 在计数器倒计时时打印到控制台。但是当它到达 0 时,"Timer Done" 不打印。

    @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")

    }
}

你做的是错误的。调用 setDate 后,计时器开始倒计时。要获取计时器的实际状态信息,您应该实例化 NSTimer 并检查它何时触发。

来自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.

这是我想到的解决方案。现在,计时器结束时的警报只是用 "Done" 打印到控制台。非常感谢用户 Prawn,因为我在此解决方案中使用了他的一些代码。

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()
}

}