whatamidoinggg
whatamidoinggg

Reputation: 11

Function when WatchKit timer ends

I have a watchkit timer,
However, I have no idea how to perform an action like a notification or segue when the timer ends.
Any ideas?

@IBOutlet var sceneTimer: WKInterfaceTimer!


override func awake(withContext context: Any?) {
    super.awake(withContext: context)
    sceneTimer.setDate(NSDate(timeIntervalSinceNow :21) as Date)

}

override func willActivate() {
    super.willActivate()
    sceneTimer.start()
}

override func didDeactivate() {
    super.didDeactivate()
}

Yes I am new to this whole thing so its not a ground-breaking code, feel free to correct.

Upvotes: 1

Views: 929

Answers (2)

Dan O'Leary
Dan O'Leary

Reputation: 946

Someone could certainly improve upon this I'm sure. But I built a little watchOS App with a Start Button, a timer and a label. Hook up your WKInterfaceTimer, WKInterfaceLabel and Button as appropriate and this code should work. You can also download the project from GitHub.

var theTimer = Timer()
var backgroundTimer = TimeInterval(15)
@IBOutlet var appleTimer: WKInterfaceTimer!
@IBOutlet var label: WKInterfaceLabel!


override func willActivate() {
    // This method is called when watch view controller is about to be visible to user
    super.willActivate()
    appleTimer.setDate(Date(timeIntervalSinceNow: 15))
    label.setText("")
}    


@IBAction func startButton() {
    let startTime = Date(timeIntervalSinceNow: 15)
    appleTimer.setDate(startTime)
    appleTimer.start()

    // This will call timerCountDown() once per second until conditions are met.
    theTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerCountDown), userInfo: nil, repeats: true)

}

func timerCountDown() {
    backgroundTimer -= 1.0
    print(backgroundTimer)
    if backgroundTimer == 0 {
        theTimer.invalidate()
        appleTimer.stop()

        // You could call an Alert Action here.
        label.setText("Timer Done!")
    }

}

Upvotes: 1

David Pasztor
David Pasztor

Reputation: 54745

WKInterfaceTimer is just a label that can be used to display a countdown. It has no associated function that is called by the system once the countdown reaches zero. You need to configure a Timer object with the same target date if you need to know when the countdown reaches 0.

Upvotes: 0

Related Questions