如何快速开始使用Healthkit获得睡眠时间?

时间:2019-01-22 14:33:22

标签: ios iphone swift health-kit

我想获取健康套件中的所有睡眠数据,苹果建议使用HKStatisticsCollectionQuery查询进行集合类型查询,但是我尝试使用以下代码进行步进,步行距离可以正常工作,但是当我使用相同的代码进行睡眠时在收集时间中,数量类型无法确认错误的到来,因为睡眠是类别而非数量。

如何获取给定时段的睡眠数据?我可以获取特定日期的睡眠数据,但无法获取睡眠数据。

let calendar = NSCalendar.currentCalendar()

let interval = NSDateComponents()
interval.day = 7

// Set the anchor date to Monday at 3:00 a.m.
let anchorComponents = calendar.components([.Day, .Month, .Year, .Weekday], 
fromDate: NSDate())


let offset = (7 + anchorComponents.weekday - 2) % 7
anchorComponents.day -= offset
anchorComponents.hour = 3

guard let anchorDate = calendar.dateFromComponents(anchorComponents) else {
  fatalError("*** unable to create a valid date from the given components ***")
}

 guard let quantityType = 
HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount) else 
{
   fatalError("*** Unable to create a step count type ***")
}

// Create the query
let query = HKStatisticsCollectionQuery(quantityType: quantityType,
                                    quantitySamplePredicate: nil,
                                    options: .CumulativeSum,
                                    anchorDate: anchorDate,
                                    intervalComponents: interval)

   // Set the results handler
   query.initialResultsHandler = {
   query, results, error in

   guard let statsCollection = results else {
    // Perform proper error handling here
    fatalError("*** An error occurred while calculating the statistics: \(error?.localizedDescription) ***")
}

let endDate = NSDate()

guard let startDate = calendar.dateByAddingUnit(.Month, value: -3, toDate: endDate, options: []) else {
    fatalError("*** Unable to calculate the start date ***")
}

// Plot the weekly step counts over the past 3 months
statsCollection.enumerateStatisticsFromDate(startDate, toDate: endDate) { [unowned self] statistics, stop in

    if let quantity = statistics.sumQuantity() {
        let date = statistics.startDate
        let value = quantity.doubleValueForUnit(HKUnit.countUnit())

        // Call a custom method to plot each data point.
        self.plotWeeklyStepCount(value, forDate: date)
    }
  }
 }

 healthStore.executeQuery(query)

我从this apple dock link处获取了以上代码。

0 个答案:

没有答案