简体   繁体   English

如何使用HealthKit从特定日期准确获取24小时睡眠数据?

[英]How to get exactly 24 hours of sleep data from a specific date with HealthKit?

I'm familiar with the typical means of getting sleep data, but it's proving somewhat more difficult to get hours of sleep for a specific 24 hour window. 我熟悉获取睡眠数据的典型方法,但是事实证明,要在特定的24小时窗口内获取几个小时的睡眠会更加困难。

I can setup a predicate to get samples that start or end within a certain time, but many times these samples cross date boundaries. 我可以设置谓词来获取在一定时间内开始或结束的样本,但是很多时候这些样本跨越日期边界。 If I go to bed at 10PM and wake up at 4AM, then sleep from 5AM to 8AM, it's difficult to scope the 10-4 sample to get just the part from yesterday. 如果我在晚上10点上床睡觉,然后在凌晨4点醒来,然后从凌晨5点睡到8点,很难确定10-4样本的范围以获取昨天的一部分。

A typical predicate might look something like this (using the following date extension): 一个典型的谓词可能看起来像这样(使用以下日期扩展名):

extension Date {
    var today: Date {
        return Calendar.current.date(byAdding: .day, value: 0, to: midnight)!
    }
    var yesterday: Date {
        return Calendar.current.date(byAdding: .day, value: -1, to: midnight)!
    }
}

let predicate = HKQuery.predicateForSamples(withStart: Date().yesterday, end: Date().today, options: [])

And then get a sample, and do something to get the seconds/minutes/hours: 然后获取样本,并执行一些操作以获取秒/分钟/小时:

let seconds = sample.endDate.timeIntervalSince(sample.startDate)

But this causes issues when the start date isn't necessarily from yesterday, or the end date isn't necessarily before today. 但这会导致问题,开始日期不一定是昨天,或者结束日期不一定是今天。

I can start doing some special casing around start and end dates, but it gets somewhat complicated. 我可以在开始日期和结束日期附近进行一些特殊的替换,但是它变得有些复杂。 Is there a simple way to just get the hours sleep from yesterday (the exact 24 hour window from midnight to midnight)? 是否有一种简单的方法可以让您从昨天开始一直保持睡眠状态(从午夜到午夜的准确24小时窗口)? I feel like I must be misunderstanding some basic about sleep queries, or the time math around this. 我觉得我一定会误解一些关于睡眠查询的基本知识,或者关于时间的数学知识。

HealthKit does not have a way to interpolate the results of queries for HKCategorySample types. HealthKit无法对HKCategorySample类型的查询结果进行插值。 Your queries must match the entirety of the sleep samples you want to work with, and you'll have to do the math yourself to figure out how much of the sample falls in the date interval you're interested in. 您的查询必须与您要使用的整个睡眠样本匹配,并且您必须自己进行数学运算以找出在您感兴趣的日期间隔内有多少样本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM