首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使iwatch应用程序主动传输运动和健康数据

如何使iwatch应用程序主动传输运动和健康数据
EN

Stack Overflow用户
提问于 2022-08-29 14:17:55
回答 1查看 45关注 0票数 0

我正在开发一个应用程序,它需要加速度计、陀螺仪和计步器数据以及心率。我正在将这些数据从iwatch传输到iPhone,然后从iPhone,我需要通过MQTT协议同步这些数据。现在我的问题是,一旦iwatch窗口关闭我的应用程序。我正在使用核心运动和现场锻炼会议。有人能帮助我如何保持iwatch应用程序活动或从非活动模式传输上述数据吗?

EN

回答 1

Stack Overflow用户

发布于 2022-09-06 09:12:00

以下是我的解决方案,可以帮助您:

参考文献:https://developer.apple.com/documentation/healthkit/workouts_and_activity_rings/running_workout_sessions

  1. Setup HKWorkoutSessionCoreMotion listener

代码语言:javascript
复制
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. 在后台模式下启用“锻炼处理”:

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73530229

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档