Stack Overflow Asked by Mert Köksal on December 7, 2020
That is the link of the project https://github.com/m3rtkoksal/WalkerCoin
I am trying to reach all the historical step counts but when I change startDate
value from -7 to something bigger than -7 I am getting Fatal error: Can't remove first element from an empty collection: file Swift/RangeReplaceableCollection.swift, line 624
I allowed all the necessary permissions from info.plist and added Healthkit from signing&capabilities.
If I try only 7 days back it works but when I increase that value it crashes.
import SwiftUI
import HealthKit
struct StepView: View {
private var healthStore: HealthStore?
@State private var selectedDay = Step(count: 0, date: Date())
@State private var steps: [Step] = [Step]()
init() {
healthStore = HealthStore()
}
private func updateUIFromStatistics(_ statisticsCollection: HKStatisticsCollection) {
steps = []
let now = Date()
let offset = -7
let startDate = Calendar.current.date(byAdding: .day, value: offset, to: Date())!
statisticsCollection.enumerateStatistics(from: startDate, to: now) { (statistics, stop) in
let count = statistics.sumQuantity()?.doubleValue(for: .count())
let step = Step(count: Int(count ?? 0), date: statistics.startDate)
steps.append(step)
}
}
var body: some View {
ZStack(alignment: .leading) {
Image("stepsTabBG")
.resizable()
.ignoresSafeArea(.all)
VStack {
HStack {
ScrollView(.horizontal) {
HStack(spacing: 30) {
ForEach(steps, id: .id) { day in
Text("(Calendar.current.dateComponents([.day], from: day.date).day ?? 0 )")
.foregroundColor(self.selectedDay.date == day.date ? Color.red : Color.black)
.onTapGesture {
selectedDay = day
}
}
}
}
.frame(width: UIScreen.main.bounds.width / 2)
.padding(10)
Spacer()
}
CircularProgress(steps: selectedDay.count)
and this is my HealthStore
import HealthKit
extension Date {
static func mondayAt12AM() -> Date {
return Calendar(identifier: .iso8601).date(from: Calendar(identifier: .iso8601).dateComponents([.yearForWeekOfYear, .weekOfYear], from: Date()))!
}
}
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 offset = -7
let startDate = Calendar.current.date(byAdding: .day, value: offset, to: Date())!
let anchorDate = Date.mondayAt12AM()
let daily = DateComponents(day: 1)
let predicate = HKQuery.predicateForSamples(withStart: startDate, end: Date(), options: .strictStartDate)
query = HKStatisticsCollectionQuery(quantityType: stepType, quantitySamplePredicate: predicate, options: .cumulativeSum, anchorDate: anchorDate, intervalComponents: daily)
query!.initialResultsHandler = { query, statisticsCollection, error in
completion(statisticsCollection)
}
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)
}
}
}
And that is the error description after the crash.
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP