我正在尝试在Apple Watch(OS2)上制作一个番茄钟应用程序。我想在倒计时结束后触发通知,在第一步我试图在控制台中打印一些单词,但它仍然不起作用。如何使用NSTimeInterval
来节省剩余时间?
import WatchKit
import Foundation
class InterfaceController: WKInterfaceController {
let countdown:NSTimeInterval = 1501
var timerRunning = false
@IBOutlet var pauseButton: WKInterfaceButton!
@IBOutlet var timer: WKInterfaceTimer!
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
}
override func willActivate() {
super.willActivate()
}
override func didDeactivate() {
super.didDeactivate()
}
@IBAction func startPomodoro() {
let date = NSDate(timeIntervalSinceNow: countdown)
timer.setDate(date)
timer.start();
WKInterfaceDevice.currentDevice().playHaptic(.Start)
WKInterfaceDevice.currentDevice().playHaptic(.Start)
}
@IBAction func resetPomodoroTimer() {
timer.stop()
let resetCountdown:NSTimeInterval = 1501
let date = NSDate(timeIntervalSinceNow: resetCountdown)
timer.setDate(date)
WKInterfaceDevice.currentDevice().playHaptic(.Retry)
WKInterfaceDevice.currentDevice().playHaptic(.Retry)
}
@IBAction func pausePomodoro() {
timer.stop()
if !timerRunning{
pauseButton.setTitle("Restart")
}
WKInterfaceDevice.currentDevice().playHaptic(.Stop)
WKInterfaceDevice.currentDevice().playHaptic(.Stop)
}
func showNotification(){
if countdown < 1490
{
print("Notification")
WKInterfaceDevice.currentDevice().playHaptic(.Success)
WKInterfaceDevice.currentDevice().playHaptic(.Success)
}
}
}
答案 0 :(得分:0)
要在WKInterfaceTimer
完成后触发通知,您必须添加具有相同时间间隔的NSTimer
。你可以同时启动两个,当NSTimer激活时,你知道WKInterfaceTimer也完成了。恕我直言,这不是一个非常优雅的解决方案,但在Apple的文档中建议,所以显然没有其他方法可以做到这一点。
如果要添加暂停/重启功能,则必须跟踪用户点击“暂停”并停止两个计时器的剩余时间。当用户再次启动计时器时,您将两个计时器都设置为剩余时间并启动它们。
以下是一个具有暂停/重启功能的工作示例(它有一个连接到button
插座的WKInterfaceButton和didPressButton:
操作:
enum TimerState {
case Idle, Running, Paused, Finished
}
class InterfaceController: WKInterfaceController {
let countdownDuration: NSTimeInterval = 10
var remainingDuration: NSTimeInterval = 10
var timer: NSTimer?
var timerState = TimerState.Idle
@IBOutlet var interfaceTimer: WKInterfaceTimer!
@IBOutlet var button: WKInterfaceButton!
@IBAction func didPressButton() {
switch timerState {
case .Idle:
startTimer(remainingDuration: countdownDuration)
case .Running:
let fireDate = timer!.fireDate
remainingDuration = fireDate.timeIntervalSinceDate(NSDate())
interfaceTimer.stop()
timer?.invalidate()
button.setTitle("Continue")
timerState = .Paused
case .Paused:
startTimer(remainingDuration: remainingDuration)
case .Finished:
break
}
}
func startTimer(remainingDuration duration:NSTimeInterval) {
interfaceTimer.setDate(NSDate(timeIntervalSinceNow: duration))
interfaceTimer.start()
timer = NSTimer.scheduledTimerWithTimeInterval(duration, target: self, selector: Selector("timerDidFire:"), userInfo: nil, repeats: false)
button.setTitle("Pause")
timerState = .Running
}
func timerDidFire(timer: NSTimer) {
interfaceTimer.stop()
timerState = .Finished
WKInterfaceDevice.currentDevice().playHaptic(.Success)
}
}