【问题标题】:Extended Runtime Session in watchOSwatchOS 中的扩展运行时会话
【发布时间】:2020-03-07 17:20:59
【问题描述】:

我试图在按下按钮时启动扩展运行时会话,并在计时器用完后使其无效。 它有效——一次。但是,一旦我再次单击该按钮,就会收到一条错误消息。

我感觉我需要创建一个新的会话实例,类似于https://stackoverflow.com/a/34377802/8832949,但我不确定如何。

这是我目前尝试过的:

根据: Using Extended Runtime Sessions - Apple Documentation

我将 WatchKit Extension 中的后台模式设置为 Self Care。

所有会话相关代码:

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

第一个会话像我想要的那样开始并失效并打印到控制台中。 尝试开始新会话时,我收到以下错误消息:

2020-03-07 11:03:43.833270-0600 GymTimeTest WatchKit 扩展[8539:705092] [默认] -[WKExtendedRuntimeSession _start]:308:无法启动会话,因为状态 == WKExtendedRuntimeSessionStateInvalid。通知代表。错误为(空)

一旦应用尝试使会话无效,我会收到以下块:

会话失效后如何启动新会话?

【问题讨论】:

    标签: swift xcode watchkit watchos watchos-6


    【解决方案1】:

    在研究了Apple的SpeedySloth: Creating a Workout示例代码后,我将我的代码改成了这样:

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

    由于我是应用程序开发的新手,我还不知道为什么会这样,但确实如此。

    会话一遍又一遍地启动和失效,没有问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-25
      • 2012-03-23
      • 1970-01-01
      • 2021-04-24
      • 2021-07-24
      • 2010-10-18
      • 1970-01-01
      相关资源
      最近更新 更多