簡體   English   中英

如何保持 iwatch 應用程序處於活動狀態以傳輸運動和健康數據

[英]How to keep iwatch app active to transfer motion & health data

我正在開發一個需要加速度計、陀螺儀和計步器數據以及心率的應用程序。 我正在將這些數據從 iwatch 傳輸到 iPhone,然后從 iPhone 我需要通過 MQTT 協議同步這些數據。 現在我的問題是,一旦 iwatch window 禁用我的應用程序終止。 我正在使用核心運動和現場鍛煉 session。 誰能幫助我如何保持 iwatch 應用程序處於活動狀態或從非活動模式傳輸上述數據?

這是我的解決方案,可以幫助您:

參考: https://developer.apple.com/documentation/healthkit/workouts_and_activity_rings/running_workout_sessions

  1. 設置HKWorkoutSessionCoreMotion監聽器
import WatchKit
import Foundation
import CoreMotion
import HealthKit

enum VelocityVector: Int {
    case x, y, z
}

class InterfaceController: WKInterfaceController {

    @IBOutlet weak var labelVelocity: WKInterfaceLabel!
    let coreMotion = CMMotionManager.init()
    let pool = OperationQueue.init()
    let currentSession: HKWorkoutSession?
    let healthKit = HKHealthStore()
    
    override func awake(withContext context: Any?) {
        coreMotion.accelerometerUpdateInterval = 0.1
        coreMotion.startAccelerometerUpdates(to: pool) { data, err in
            guard let _data = data else { return }
            DispatchQueue.main.async {
                self.labelVelocity.setText(String.init(format: "G-Force (x:y:z) %.3f:%.3f:%.3f", arguments: [_data.acceleration.x, _data.acceleration.y, _data.acceleration.z]))
            }
        }
        
        let config = HKWorkoutConfiguration.init()
        config.activityType = .other
        config.locationType = .unknown
        
        do {
            self.currentSession = try HKWorkoutSession.init(healthStore: self.healthKit, configuration: config)
            self.currentSession?.startActivity(with: Date())
        } catch error {
            print(error?.localizedDescription)
        }        
    }

    private func stopHKWorkoutSession() {
        self.currentSession?.stopActivity(with: Date())
        self.currentSession?.end()
    }
    
    override func willActivate() {
        // This method is called when watch view controller is about to be visible to user
    }
    
    override func didDeactivate() {
        // This method is called when watch view controller is no longer visible
    }

}
  1. 在后台模式下啟用“鍛煉處理”: 在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM