swiftxcodewatchkitwatchoswatchos-6

Extended Runtime Session in watchOS


I am trying to start an extended runtime session on press of a button, and invalidate it after a timer runs out. It works – once. Once I click the button again however, I get an error message.

I have a feeling I need to create a new session instance, similar to https://stackoverflow.com/a/34377802/8832949, but I am not sure how.

Here is what I tried so far:

According to: Using Extended Runtime Sessions - Apple Documentation

I set the background mode in WatchKit Extension to Self Care. Background Mode: Self Care

All session related code:

class InterfaceController: WKInterfaceController, WKExtendedRuntimeSessionDelegate {

    var session = WKExtendedRuntimeSession()
    var time = 15
    var timer = Timer()

    func extendedRuntimeSession(_ extendedRuntimeSession: WKExtendedRuntimeSession, didInvalidateWith reason: WKExtendedRuntimeSessionInvalidationReason, error: Error?) {
        print("Session stopped at", Date())
    }

    func extendedRuntimeSessionDidStart(_ extendedRuntimeSession: WKExtendedRuntimeSession) {
        print("Session started at", Date())
    }


    @IBAction func startTimerButtonPressed() {
        session.delegate = self
        session.start()
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(action), userInfo: nil, repeats: true)
    }

    @objc func action() {

        if time < 1 {
        WKInterfaceDevice.current().play(.stop)
        timer.invalidate()
        time = 15
        session.invalidate()
    } else {
        time -= 1
    }
}

The first session starts and invalidates like I want it to and prints into the console. When trying to start a new session I get the following error message:

2020-03-07 11:03:43.833270-0600 GymTimeTest WatchKit Extension[8539:705092] [default] -[WKExtendedRuntimeSession _start]:308: Unable to start sessions because state == WKExtendedRuntimeSessionStateInvalid. notifying delegate . Error is (null)

Once the app tries to invalidate the session I get the following blocks:

Console

How do I start a new session once a session is invalidated?


Solution

  • After studying Apple's SpeedySloth: Creating a Workout example code, I changed my code to this:

    class InterfaceController: WKInterfaceController, WKExtendedRuntimeSessionDelegate {
    
        var session: WKExtendedRuntimeSession!
    
        @IBAction func startTimerButtonPressed() {
            session = WKExtendedRuntimeSession()
            session.delegate = self
            session.start()
        }
    }
    

    Since I am new to app development I do not yet know why this works, but it does.

    Sessions are started and invalidated over and over again without a problem.