tatsuyamoriguchi / Sleep-Tracer

1 stars 0 forks source link

Respiratory Rate List view not displaying additional data, correctly. #69

Closed tatsuyamoriguchi closed 1 month ago

tatsuyamoriguchi commented 1 month ago

With Sleep Tracer running, adding additional Respiratory Rates to HealthKit adds extra data rows to RespiratoryRateView List. If re-launch Sleep Tracer, it shows the first data per hour, not showing or counting additional data. Examine the the logic to display the hourly Respiratory Rates.

tatsuyamoriguchi commented 1 month ago

It is calculating the average number of respiratory rates per hour.

With running the app, add more respiratory data in Health app. Tap other TabItem, and go back to Respiratory Rates view. Every time you do this, it duplicates rate data rows to the view. If relaunched, it displays rates per hour, correctly.

It actually duplicates rate data rows to the view by just tapping another BarItem and back to the Respiratory Rates view.

tatsuyamoriguchi commented 1 month ago

Making SwiftUI views refreshable

tatsuyamoriguchi commented 1 month ago

Working with Identifiable items in SwiftUI UUID is already implemented.

tatsuyamoriguchi commented 1 month ago

List .refreshable {} not working

tatsuyamoriguchi commented 1 month ago

The issue with your Swift function is that every time it is executed, it appends new data to the counts array without clearing the previous data. This leads to duplicates being added to the counts array each time the function runs.

To fix this, you should clear the counts array at the beginning of the function. Here's the corrected version of your function:

private func updateUIFromStatistics(_ statisticsCollection: HKStatisticsCollection) {

    let startDate = Calendar.current.date(byAdding: .day, value: -7, to: Date())!
    let endDate = Date()

    // Clear the counts array to prevent duplicates
    counts.removeAll()

    statisticsCollection.enumerateStatistics(from: startDate, to: endDate) { (statistics, stop) in

        let count = statistics.averageQuantity()?.doubleValue(for: HKUnit(from: "count/min"))

        let respiratory = RespiratoryRate(count: Int(count ?? 0), date: statistics.startDate)
        counts.append(respiratory)
    }

    counts = counts.sorted { $0.date > $1.date }
}

In this updated function, counts.removeAll() is called at the beginning, which clears any existing data from the counts array. This ensures that only the new data from the latest call to updateUIFromStatistics is added to the array, thus preventing duplicates.