如何每天从Healthkit中查询总步数并显示在SwiftUI文本视图中?

问题描述 投票:0回答:1

[我正在尝试获取用户今天已执行的步骤总数,并在Apple Watch屏幕上的SwiftUI文本视图中显示此步骤数。

我在网上找到的所有代码段均无效。似乎hkstatisticscollectionquery应该是用来获取这种类型的数据的工具,但是Apple文档中的代码不适用于我。我已经请求用户允许从healthkit中读取步骤数据,因此所需要做的就是查询此数据并将其放入SwiftUI文本视图中。以下是Apple的开发人员文档,其中包含我无法使用的代码。

https://developer.apple.com/documentation/healthkit/hkstatisticscollectionquery

这是Apple提供的用于查询对我不起作用的步骤的代码。

let calendar = NSCalendar.currentCalendar()

let interval = NSDateComponents()
interval.day = 7

// Set the anchor date to Monday at 3:00 a.m.
let anchorComponents = calendar.components([.Day, .Month, .Year, .Weekday], fromDate: NSDate())


let offset = (7 + anchorComponents.weekday - 2) % 7
anchorComponents.day -= offset
anchorComponents.hour = 3

guard let anchorDate = calendar.dateFromComponents(anchorComponents) else {
    fatalError("*** unable to create a valid date from the given components ***")
}

guard let quantityType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount) else {
    fatalError("*** Unable to create a step count type ***")
}

// Create the query
let query = HKStatisticsCollectionQuery(quantityType: quantityType,
                                        quantitySamplePredicate: nil,
                                        options: .CumulativeSum,
                                        anchorDate: anchorDate,
                                        intervalComponents: interval)

// Set the results handler
query.initialResultsHandler = {
    query, results, error in

    guard let statsCollection = results else {
        // Perform proper error handling here
        fatalError("*** An error occurred while calculating the statistics: \(error?.localizedDescription) ***")
    }

    let endDate = NSDate()

    guard let startDate = calendar.dateByAddingUnit(.Month, value: -3, toDate: endDate, options: []) else {
        fatalError("*** Unable to calculate the start date ***")
    }

    // Plot the weekly step counts over the past 3 months
    statsCollection.enumerateStatisticsFromDate(startDate, toDate: endDate) { [unowned self] statistics, stop in

        if let quantity = statistics.sumQuantity() {
            let date = statistics.startDate
            let value = quantity.doubleValueForUnit(HKUnit.countUnit())

            // Call a custom method to plot each data point.
            self.plotWeeklyStepCount(value, forDate: date)
        }
    }
}

healthStore.executeQuery(query)

如何从Healthkit中查询用户今天已执行的步骤总数并显示在SwiftUI文本视图中?

swift watchkit health-kit
1个回答
0
投票

根据Xcode 11.2,您的代码有些过时,但是它在Mac上运行并返回正确的数据。这是我为了使其更新而进行的更改;

func stepstest()
{
    let calendar = Calendar.current

    let interval = NSDateComponents()
    interval.day = 7

    // Set the anchor date to Monday at 3:00 a.m.
    var anchorComponents = calendar.dateComponents([.day, .month, .year, .weekday], from: Date())


    var offset = (7 + anchorComponents.weekday! - 2) % 7
    anchorComponents.day! -= offset
    anchorComponents.hour = 3
    //comp = Calendar.current.dateComponents([.year], from: Date())
    //let startOfMonth = Calendar.current.date(from: comp)!

    guard let anchorDate = Calendar.current.date(from: anchorComponents) else {
        fatalError("*** unable to create a valid date from the given components ***")
    }

    guard let quantityType = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount) else {
        fatalError("*** Unable to create a step count type ***")
    }

    // Create the query
    let query = HKStatisticsCollectionQuery(quantityType: quantityType,
                                            quantitySamplePredicate: nil,
                                            options: .cumulativeSum,
                                            anchorDate: anchorDate,
                                            intervalComponents: interval as DateComponents)

    // Set the results handler
    query.initialResultsHandler = {
        query, results, error in

        guard let statsCollection = results else {
            // Perform proper error handling here
            fatalError("*** An error occurred while calculating the statistics: \(error?.localizedDescription) ***")
        }

        let endDate = Date()


        guard let startDate = Calendar.current.date(byAdding: .month, value: -3, to: endDate) else {
            fatalError("*** Unable to calculate the start date ***")
        }

        // Plot the weekly step counts over the past 3 months
        statsCollection.enumerateStatistics(from: startDate, to: endDate) { [unowned self] statistics, stop in

            if let quantity = statistics.sumQuantity() {
                let date = statistics.startDate
                let value = quantity.doubleValue(for: HKUnit.count())

                // Call a custom method to plot each data point.
                 self.plotWeeklyStepCount(value, forDate: date)
            }
        }
    }

    healthStore.execute(query)
}
© www.soinside.com 2019 - 2024. All rights reserved.