ios - 访问 Apple Watch 中的心率传感器 - HealthKit 不返回值

标签 ios swift healthkit

我正在尝试从传感器实时获取心率值。下面的代码激活锻炼类(class)(我可以在 watch 上看到它),心率传感器亮起,所以它显然正在工作,但我无法访问值 updateHeartRate() 方法始终返回“未检测到 HR”。有谁知道如何解决这个问题?

let healthStore = HKHealthStore()
var workoutActive = false
var workoutSession : HKWorkoutSession?
let heartRateUnit = HKUnit(fromString: "count/min")
var anchor = HKQueryAnchor(fromValue:
Int(HKAnchoredObjectQueryNoAnchor))

func workoutSession(workoutSession: HKWorkoutSession, didChangeToState toState: HKWorkoutSessionState, fromState: HKWorkoutSessionState, date: NSDate) {
    switch toState {
    case .Running:
        workoutDidStart(date)
    case .Ended:
        workoutDidEnd(date)
    default:
        print("Unexpected state \(toState)")
    }
}

func workoutSession(workoutSession: HKWorkoutSession, didFailWithError error: NSError) {
    // Do nothing for now
    NSLog("Workout error: \(error.userInfo)")
}

func workoutDidStart(date : NSDate) {
    print("Workout did start")
    if let query = createHeartRateStreamingQuery(date) {
        print("Using query")
        healthStore.executeQuery(query)

    } else {
        print("cannot start")
    }
}

func workoutDidEnd(date : NSDate) {
    if let query = createHeartRateStreamingQuery(date) {
        healthStore.stopQuery(query)
    } else {
    }
}

func startBtnTapped() {
    if (self.workoutActive) {
        //finish the current workout
        self.workoutActive = false
        print("Finishing Workout")

        if let workout = self.workoutSession {
            healthStore.endWorkoutSession(workout)
        }
    } else {
        //start a new workout
        self.workoutActive = true
        startWorkout()

        print("Starting Workout")
    }

}

func startWorkout() {
    self.workoutSession = HKWorkoutSession(activityType: HKWorkoutActivityType.CrossTraining, locationType: HKWorkoutSessionLocationType.Indoor)
    self.workoutSession?.delegate = self
    healthStore.startWorkoutSession(self.workoutSession!)
}

func createHeartRateStreamingQuery(workoutStartDate: NSDate) -> HKQuery? {

    let predicate = HKQuery.predicateForSamplesWithStartDate(workoutStartDate, endDate: nil, options: HKQueryOptions.None)
    print("Entered query")
    guard let quantityType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate) else { return nil }

    let heartRateQuery = HKAnchoredObjectQuery(type: quantityType, predicate: nil, anchor: anchor, limit: Int(HKObjectQueryNoLimit)) { (query, sampleObjects, deletedObjects, newAnchor, error) -> Void in
        self.updateHeartRate(sampleObjects)
        print("Query is configured")
    }

    heartRateQuery.updateHandler = {(query, samples, deleteObjects, newAnchor, error) -> Void in
        self.updateHeartRate(samples)
        print("Updating sample")
        print(samples)
    }
    return heartRateQuery
}


func updateHeartRate(samples: [HKSample]?) {
    print("Entered updateHR")
    guard let heartRateSamples = samples as? [HKQuantitySample] else {

        print("No HR detected")

        return
    }

    dispatch_async(dispatch_get_main_queue()) {
        print("Enter async")
        guard let sample = heartRateSamples.first else{return}
        let value = sample.quantity.doubleValueForUnit(self.heartRateUnit)
        print(String(UInt16(value)))


        // retrieve source from sample
        print(sample.sourceRevision.source.name)

    }
}

最佳答案

您是否已请求授权从 HealthKit 读取心率样本? 如果不是,您的查询很可能会收到描述问题的错误。尝试检查初始结果处理程序和更新处理程序 block 中是否有错误。

关于ios - 访问 Apple Watch 中的心率传感器 - HealthKit 不返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35704069/

相关文章:

ios - HealthKit 在 Swift 2.0 中仅发布一次

ios - Perforce 搁置 .strings 文件会更改编码

ios - XLPagerTabStrip 标签没有获得相等的屏幕宽度 :Swift

ios - 向 iOS 添加新日历

android - Kotlin 中的 Swift 等效数据结构

ios - 通过按按钮插入 TableView 行

ios - 如何快速从 HealthKit 获取血氧饱和度?

ios - 仅在手机打开时收到静默通知

尝试添加文本字段时 iOS 8.3 UIAlertController 崩溃

swift - 使用照片框架删除相机胶卷 Assets