You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

iOS模拟器无法读取已存入HealthKit的跑步步行运动数据

问题根因

  • 你存储的是HKWorkout类型数据,仅在初始化HKWorkout时传入totalDistance参数,并不会自动在HealthKit中生成独立的distanceWalkingRunning类型样本。你当前ReadData方法查询的是独立的步行跑步距离样本,自然返回0条。

解决方案

你可以根据需求选择以下两种方案:

方案1:读取已存储的Workout关联的距离数据

将查询的样本类型改为Workout类型,拿到HKWorkout实例后直接读取它的totalDistance属性即可,修改后的查询代码参考:

func ReadWorkoutData() {
    let start = now - (86400 * 60.0)
    let end = now
    let predicate = HKQuery.predicateForSamples(withStart: start, end: end, options: [])

    guard HKHealthStore.isHealthDataAvailable() else {
        print("No data available!")
        return
    }

    let sampleType = HKObjectType.workoutType()
    let query = HKSampleQuery(
        sampleType: sampleType, predicate: predicate, limit: Int(HKObjectQueryNoLimit),
        sortDescriptors: nil
    ) { query, results, error in
        guard let workouts = results as? [HKWorkout], error == nil else {
            print("查询失败: \(error?.localizedDescription ?? "未知错误")")
            return
        }
        for workout in workouts {
            if let distance = workout.totalDistance?.doubleValue(for: HKUnit.meter()) {
                print("跑步距离: \(distance) 米, 时长: \(workout.duration) 秒")
            }
        }
        DispatchQueue.main.async {
            print("查询到的Workout数量: \(workouts.count)")
        }
    }
    healthStore.execute(query)
}

方案2:生成可直接查询的distanceWalkingRunning独立样本

保存Workout成功后,额外构造对应的距离样本存入HealthKit,之后你原来的ReadData方法就能查到数据,修改后的保存代码参考:

func SaveData() {
  let configuration = HKWorkoutConfiguration()
  configuration.activityType = .running
  configuration.locationType = Int.random(in: 0..<2) == 0 ? .indoor : .outdoor

  let startDate = now - (86400 * 60.0)
  let duration = 120.0
  let endDate = startDate + duration
  let quantity = HKQuantity(unit: HKUnit.kilocalorie(), doubleValue: 20.0)
  let distance = HKQuantity(unit: HKUnit.meter(), doubleValue: 1200)

  let workout = HKWorkout(
    activityType: configuration.activityType, start: startDate, end: endDate, duration: duration,
    totalEnergyBurned: quantity, totalDistance: distance,
    metadata: [HKMetadataKeyIndoorWorkout: true])

  healthStore.save(workout) { success, _ in
    if success {
      print("SAVED WORKOUT!!!")
      // 新增:保存独立的步行跑步距离样本
      let distanceType = HKQuantityType.quantityType(forIdentifier: .distanceWalkingRunning)!
      let distanceSample = HKQuantitySample(
          type: distanceType,
          quantity: distance,
          start: startDate,
          end: endDate
      )
      healthStore.save(distanceSample) { sampleSuccess, _ in
          if sampleSuccess {
              print("距离样本保存成功")
          }
      }
    } else {
      print("COULD NOT SAVE WORKOUT!!!")
    }
  }
}

其他校验点

可调用healthStore.authorizationStatus(for: type)接口确认对应权限的状态确实为.sharingAuthorized,避免用户手动拒绝权限导致的查询异常。

内容的提问来源于stack exchange,提问作者Mehmet Alpsoy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 07:06:04