如何从“健康”应用程序访问和阅读步行事件?

时间:2019-02-13 18:53:11

标签: ios swift health-kit

启动“健康”应用程序时,可以看到一段时间内我走路或跑步的整个距离,并查看带有单独事件的详细信息。但是,当我尝试使用HealthKit在应用程序中进行所有步行锻炼时,根本没有样品。

这是否意味着我无法访问Apple的Health应用程序保存的锻炼,或者它们不是锻炼?

这是我的代码:

func fetchData() {

    guard HKHealthStore.isHealthDataAvailable() else {
        throwError(HealthTrackerError.notAvailableOnDevice)
        return
    }

    let type = HKWorkoutType.workoutType()

    let completion = { [weak self] (isAuthorized: Bool, error: Error?) in
        DispatchQueue.main.async { [weak self] in
            isAuthorized ? self?.fetchData(type) : self?.throwError(error)
        }
    }

    switch HKHealthStore().authorizationStatus(for: type) {
    case .notDetermined:
        HKHealthStore().requestAuthorization(toShare: [type],
                                             read: [type],
                                             completion: completion)
    case .sharingAuthorized:
        fetchData(type)
    case .sharingDenied:
        throwError(HealthTrackerError.accessDenied)
    }
}

private func fetchData(_ workout: HKWorkoutType) {

    let predicate = HKQuery.predicateForWorkouts(with: .walking)

    let query = HKSampleQuery(sampleType: workout, predicate: predicate, limit: 0, sortDescriptors: nil) { [weak self] (query, samples, error) in

        guard let workouts = samples as? [HKWorkout] else {
            self?.throwError(error)
            return
        }

        // No workouts were found

        self?.values = workouts
            .map { $0.totalEnergyBurned?.doubleValue(for: HKUnit.kilocalorie()) }
            .filter { $0 != nil }
            .map { $0! }
    }

    HKHealthStore().execute(query)
}

感谢MwcsMac的链接,这是适用于我的更新代码。

func fetchData() {

    guard HKHealthStore.isHealthDataAvailable() else {
        throwError(HealthTrackerError.notAvailableOnDevice)
        return
    }

    guard let type = HKQuantityType.quantityType(forIdentifier: .distanceWalkingRunning) else {
        throwError(HealthTrackerError.dataTypeNotAvailable)
        return
    }

    let completion = { [weak self] (isAuthorized: Bool, error: Error?) in
        DispatchQueue.main.async { [weak self] in
            isAuthorized ? self?.fetchData(type) : self?.throwError(error)
        }
    }

    switch HKHealthStore().authorizationStatus(for: type) {
    case .notDetermined:
        HKHealthStore().requestAuthorization(toShare: [type],
                                             read: [type],
                                             completion: completion)
    case .sharingAuthorized:
        fetchData(type)
    case .sharingDenied:
        throwError(HealthTrackerError.accessDenied)
    }
}

private func fetchData(_ quantityType: HKQuantityType) {

    let predicate = HKQuery.predicateForSamples(withStart: startDate,
                                                end: currentDate,
                                                options: [])


    let query = HKSampleQuery(sampleType: quantityType, predicate: predicate, limit: HKObjectQueryNoLimit, sortDescriptors: nil) { [weak self] (query, samples, error) in

        guard let samples = samples as? [HKQuantitySample] else {
            self?.throwError(error)
            return
        }

        self?.values = samples.map { $0.quantity.doubleValue(for: HKUnit.meter()) }
    }

    HKHealthStore().execute(query)
}

0 个答案:

没有答案