1

我在其中一个选项卡中显示每日步数信息。不幸的是,当我再次选择步骤选项卡时,它会在前一个数据下方添加一个相同的数据。

在此处输入图像描述

我试图通过切换布尔值来解决它。但这也无济于事。

import SwiftUI
import HealthKit

struct StepView: View {
    private var healthStore: HealthStore?
    @State private var presentClipboardView = true
    @State private var steps: [Step] = [Step]()
    init() {
        healthStore = HealthStore()
    }
    private func updateUIFromStatistics(_ statisticsCollection: HKStatisticsCollection) {
        let now = Date()
        let startOfDay = Calendar.current.startOfDay(for: now)
        statisticsCollection.enumerateStatistics(from: startOfDay, to: now) { (statistics, stop) in
            let count = statistics.sumQuantity()?.doubleValue(for: .count())
            let step = Step(count: Int(count ?? 0), date: statistics.startDate, wc: Double(count ?? 0 / 1000 ))
            steps.append(step)
        }
    }
    var body: some View {  
        VStack {
            ForEach(steps, id: \.id) { step in
                VStack {
                        HStack{
                            Text("WC")
                            Text("\(step.wc)")
                        }
                        HStack {
                            Text("\(step.count)")
                            Text("Total Steps")
                        }
                        Text(step.date, style: .date)
                            .opacity(0.5)
                        Spacer()
                }
            }
            .navigationBarBackButtonHidden(true)
        }
        .onAppear() {
            if let healthStore = healthStore {
                healthStore.requestAuthorization { (success) in
                    if success {
                        healthStore.calculateSteps { (statisticsCollection) in
                            if let statisticsCollection = statisticsCollection {
                                updateUIFromStatistics(statisticsCollection)
                            }
                        }
                    }
                }
            }
        }
        .onDisappear() {
            self.presentClipboardView.toggle()
        }
    }
}

阶梯模型

struct Step: Identifiable {
    let id = UUID()
    let count: Int?
    let date: Date
    let wc: Double
}

健康商店文件

class HealthStore {
    var healthStore: HKHealthStore?
    var query: HKStatisticsCollectionQuery?
    init() {
        if HKHealthStore.isHealthDataAvailable() {
            healthStore = HKHealthStore()
        }
    }
    func calculateSteps(completion: @escaping (HKStatisticsCollection?) -> Void ) {
        let stepType = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)!
        let now = Date()
        let startOfDay = Calendar.current.startOfDay(for: now)
        let daily = DateComponents(day:1)
        let predicate = HKQuery.predicateForSamples(withStart: startOfDay, end: Date(), options: .strictStartDate)
        query = HKStatisticsCollectionQuery(quantityType: stepType, quantitySamplePredicate: predicate, options: .cumulativeSum, anchorDate: startOfDay, intervalComponents: daily)
        query!.initialResultsHandler = { query, statisticCollection, error in
            completion(statisticCollection)
        }
        if let healthStore = healthStore, let query = self.query {
            healthStore.execute(query)
        }
    }
    
    func requestAuthorization(completion: @escaping (Bool) -> Void) {
        let stepType = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)!
        guard let healthStore = self.healthStore else { return completion (false) }
        healthStore.requestAuthorization(toShare: [], read: [stepType]) { (success, error) in
            completion(success)
        }
    }
}

根据我的问题,这些都是相关文件。提前致谢。

4

1 回答 1

1

steps带有注释,这@State意味着即使在重绘视图时它也会保持不变。

而且你永远不会重置它。您只附加新步骤。steps尝试清除updateUIFromStatistics

private func updateUIFromStatistics(_ statisticsCollection: HKStatisticsCollection) {
    steps = [] // remove previous values
    let now = Date()
    let startOfDay = Calendar.current.startOfDay(for: now)
    statisticsCollection.enumerateStatistics(from: startOfDay, to: now) { (statistics, stop) in
        let count = statistics.sumQuantity()?.doubleValue(for: .count())
        let step = Step(count: Int(count ?? 0), date: statistics.startDate, wc: Double(count ?? 0 / 1000 ))
        steps.append(step)
    }
}
于 2020-11-06T12:07:17.377 回答