HKWorkoutSession没有持续运行

时间:2018-04-30 21:22:23

标签: ios swift watchkit

在watchOS中,我只是想在exerciseSession运行时实时获取HR值。

func startHeartRateQuery(updateHandler: @escaping ([HKQuantitySample]?) -> Void) {
    guard let quantityType = HKObjectType.quantityType(forIdentifier: .heartRate) else {
        return
    }

    let heartRateQuery = HKAnchoredObjectQuery(type: quantityType, predicate: nil, anchor: anchor, limit: Int(HKObjectQueryNoLimit)) { (query, sampleObjects, deletedObjects, newAnchor, error) -> Void in
        guard let newAnchor = newAnchor else {return}
        self.anchor = newAnchor
        updateHandler(sampleObjects as? [HKQuantitySample])
    }

    heartRateQuery.updateHandler = {(query, samples, deleteObjects, newAnchor, error) -> Void in
        self.anchor = newAnchor!
        updateHandler(samples as? [HKQuantitySample])
    }

    healthStore.execute(heartRateQuery)
    activeDataQueries.append(heartRateQuery)
}

这就是我开始锻炼的方法。

func session(_ session: WCSession, didReceiveUserInfo userInfo: [String : Any] = [:]) {
    guard let d = delegate else {
        return
    }

    if let u = userInfo["status"] as? String {
        d.receivedWorkoutRunningStatus(u)
    }

    if let c = userInfo["clock"] as? String {
        d.receiveWorkoutRestPeriodClock(c)
    }
}

您可以在InterfaceController上找到receivedWorkoutRunningStatus函数。 这是InterfaceController.swift,这是Watch App上的第一个屏幕。

class InterfaceController: WKInterfaceController, HKWorkoutSessionDelegate {

@IBOutlet var lblHeartRate: WKInterfaceLabel!
@IBOutlet var lblSplitIntervalNumber: WKInterfaceLabel!
@IBOutlet var lblRestPeriodClock: WKInterfaceLabel!

private let healthStoreManager = WatchHealthKitManager()
private let parentConnector = ParentConnector()
private var workoutSession: HKWorkoutSession!

override func awake(withContext context: Any?) {
    super.awake(withContext: context)

    // Create a workout session with the workout configuration
    do {
        let workoutConfiguration = HKWorkoutConfiguration()
        workoutConfiguration.locationType = .indoor
        workoutConfiguration.activityType = .rowing

        workoutSession = try HKWorkoutSession(configuration: workoutConfiguration)
    } catch {
        fatalError(error.localizedDescription)
    }

    //// initial setup
    parentConnector.activate()
    parentConnector.delegate = self
    workoutSession.delegate = self
}    
// MARK: - Data Accumulation

private func startAccumulatingData() {
    healthStoreManager.startHeartRateQuery() { quantitySamples in
        DispatchQueue.main.async {
            guard !self.isPaused() else {
                return
            }

            guard let heartRateSamples = quantitySamples else {
                return
            }

            let hrUnit = HKUnit(from: "count/min")
            guard let sample = heartRateSamples.first else {
                return
            }

            let value = sample.quantity.doubleValue(for: hrUnit)
            self.updateHeartRate(value: value)
            self.parentConnector.transfer(value: value)
        }
    }
}

func workoutSession(_ workoutSession: HKWorkoutSession,
                    didChangeTo toState: HKWorkoutSessionState,
                    from fromState: HKWorkoutSessionState,
                    date: Date) {
    switch (toState) {
    case .running:
        startAccumulatingData()
    case .ended:
        stopAccumulatingData()
    default:
        print("Error")
    }
}
func receivedWorkoutRunningStatus(_ status: String) {
    if (status == "Start") {
        healthStoreManager.start(workoutSession)
    } else if (status == "Finish") {
        healthStoreManager.end(workoutSession)
        lblHeartRate.setText("No Active Workout")
    }

    DispatchQueue.main.async {
        self.lblSplitIntervalNumber.setText(status)
    }
}

在iPhone应用程序上,我使用transferUserInfo函数发送“开始”字符串以触发workoutSession开始。这不能正常工作,它有时只能起作用,它非常不一致。

如果您有任何建议或其他方法,我将不胜感激。

提前谢谢。

0 个答案:

没有答案