AnswerBun.com

Thread 1: Fatal error: Can't remove last element from an empty collection SwiftUI

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.

enter image description here

Add your own answers!

Related Questions

Main Thread Checker Error: Double to UILabel Fails Swift

1  Asked on December 13, 2021 by nisse82

     

Can’t create bitmap without Color space android

1  Asked on December 13, 2021 by iheb-404-notfound

       

fetch id who have register all adv

1  Asked on December 11, 2021 by user13974528

   

Is there a better way to write this snippet in python?

3  Asked on December 11, 2021 by paulo-sergio-schlogl

 

How to set if-else statement in a React function Return()?

4  Asked on December 11, 2021 by buffaurus

   

Check if the next item is 1 unit longer (Javascript)

3  Asked on December 11, 2021 by ekhi-arzac

   

adding onclick to an array of items

5  Asked on December 11, 2021 by helpmepiliizz

       

How to make sure only 1 thread is running? C++

1  Asked on December 11, 2021 by lordi1000

   

Ask a Question

Get help from others!

© 2022 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP, SolveDir