Date 线程1:致命错误:Can';t从空集合SwiftUI中删除最后一个元素
这是该项目的链接 我试图达到所有历史步骤计数,但当我将Date 线程1:致命错误:Can';t从空集合SwiftUI中删除最后一个元素,date,swiftui,healthkit,Date,Swiftui,Healthkit,这是该项目的链接 我试图达到所有历史步骤计数,但当我将startDate值从-7更改为大于-7时,我得到了致命错误:无法从空集合中删除第一个元素:文件Swift/rangereplacablecollection.Swift,第624行 我从info.plist获得了所有必要的权限,并从signing&capabilities中添加了Healthkit 如果我只在7天前尝试,它会工作,但当我增加该值时,它会崩溃 import SwiftUI import HealthKit struct S
startDate
值从-7更改为大于-7时,我得到了致命错误:无法从空集合中删除第一个元素:文件Swift/rangereplacablecollection.Swift,第624行
我从info.plist获得了所有必要的权限,并从signing&capabilities中添加了Healthkit
如果我只在7天前尝试,它会工作,但当我增加该值时,它会崩溃
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)
这是我的健康商店
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)
}
}
}
这就是崩溃后的错误描述
尝试在DispatchQueue.main.async中添加append语句。这对我有用。希望它也能对你起作用。我也有同样的问题。我正准备发帖,直到看到你的帖子。你能弄明白吗?没有什么。我甚至为这个问题开始了一个悬赏,但是悬赏过期了。不要使用append,试着通过数组索引插入元素。到目前为止,这对我很有效。但老实说,我不知道为什么它会起作用。
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)
DispatchQueue.main.async {
steps.append(step)
}
}