在HKStatisticsCollectionQuery

时间:2017-02-23 01:33:17

标签: ios swift health-kit

我正在尝试从Health Kit检索步骤数据,并在每次数据更改时获取更新。

但是当HKHealthStore在查询中调用其执行方法时,应用程序崩溃:

enter image description here

我不知道为什么。欢迎任何帮助。

这是我的代码:

func sretrieveRealTimeSteps(completion: @escaping (Int) -> Void) {
    let calendar = Calendar.current

    var interval = DateComponents()
    interval.day = 1

    var anchorComponents = calendar.dateComponents([.day, .month, .year, .weekday], from: Date())
    anchorComponents.hour = 0

    guard let anchorDate = calendar.date(from: anchorComponents) else { completion(0); return }
    guard let quantityType = HKObjectType.quantityType(forIdentifier: .stepCount) else { completion(0); return }

    let realTimeQuery = HKStatisticsCollectionQuery(quantityType: quantityType,
                                                    quantitySamplePredicate: nil,
                                                    options: .cumulativeSum,
                                                    anchorDate: anchorDate,
                                                    intervalComponents: interval)

    realTimeQuery.statisticsUpdateHandler = { query, statistics, results, error in
        guard let statsCollection = results else {
            completion(0)
            return
        }

        statsCollection.enumerateStatistics(from: Date(), to: Date()) { statistics, stop in
            if let quantity = statistics.sumQuantity() {
                let value = quantity.doubleValue(for: HKUnit.count())
                completion(Int(value)) 
            } else {
                completion(0) 
            }
        }
    }

    healthKitStore.execute(realTimeQuery)
}

此外,当我使用一次查询时,没有问题:

query.initialResultsHandler = { query, results, error in
    guard let statsCollection = results else {
        NotificationView.showHealthKitRetrieveInfoFailedNotification()
        completion(nil, error)
        return
    }

    var values = [Int]()

    let endDate = Date()
    let startDate = calendar.date(byAdding: .day, value: -6, to: endDate) ?? Date()

    statsCollection.enumerateStatistics(from: startDate, to: endDate) { statistics, stop in
        if let quantity = statistics.sumQuantity() {
            let date = statistics.startDate
            let value = quantity.doubleValue(for: HKUnit.count())

            values.append(Int(value))

            if date.isSameDayThan(endDate, timeZone: TimeZone.current) { 
                completion(values, nil) 
            }
        } else {
            values.append(0)

            if values.count == 7 {
                stop.pointee = true
                completion(values, nil)
            }
        }
    }
}

编辑:Stacktrace

enter image description here

0 个答案:

没有答案