iOS HealthKit to track real time sleep states - ios

I know that HealthKit can retrieve sleep states based on some samples given start and end time. But I wonder if it can give a current realtime status of the sleep state, meaning just retrieving the current state instead. Or is it using some algorithm and this requires several values and that's why all I can find is about taking samples with some time gap in middle?
let sleepSampleType = HKCategoryType(.sleepAnalysis)
let sleepCategory = HKCategoryValueSleepAnalysis.asleepDeep.rawValue
let deepSleepSample = HKCategorySample(type: sleepSampleType,
value:sleepCategory,
start: startDate,
end: endDate)

Sleep stages data is not available in real-time. You can only read it after the user wakes up and the samples are written.

Related

Sleep Tracking and Analysis with Apple Healthkit

I'm building an application for sleep analysis using Apple Healthkit and wish to retrieve nightly sleep statistics (time in REM, deep, light etc). The apple developer video gives the following code to retrieve samples in all sleep stages...
let stagePredicate = HKCategoryValueSleepAnalysis.predicateForSamples(equalTo: .allAsleepValues)
let queryPredicate = HKSamplePredicate.sample(type: HKCategoryType(.sleepAnalysis), predicate: stagePredicate)
let sleepQuery = HKSampleQueryDescriptor(predicates: [queryPredicate], sortDescriptors: [])
// Run the query
let sleepSamples = try async sleepQuery.result(for: healthStore)
but how do I compute the time in each of the stages for the previous night? I'm very new to healthkit so any help would be appreciated.
To compute the time in each stage you'll want to iterate over the samples and check the category value. You can keep a time interval per stage and increment it based on the duration of the sample you're looking at.
The tricky part is determining what "previous night" is. Try defining equally sized buckets where you will count all samples in that bucket as part of the same "sleep session" (e.g. 6pm - 6pm instead of 12am - 12am).

HealthKit - Display Sleep

I am trying to display the sleep from the HealthKit. I am using AppCore
to display other HKQuantity. I use the following for HKQuantities like Steps, etc.
[[APCScoring alloc] initWithHealthKitQuantityType:HKQuantityType
unit:[HKUnit countUnit]
numberOfDays:-kNumberOfDaysToDisplay];
My issue is that sleep data is not a HealthKitQuantityType and I can't use HKStatisticsCollectionQuery.
I am looking to display HKCategoryValueSleepAnalysisAsleep.
As you probably figured out, Healthkit sleep analysis is not quantitative.
As describe in the Apple documentation you have only 3 states: inBed, aSleep or awake.
I've got same question and to work around, I count minutes aSleep versus minutes inBed and minutes awake (depending of what's relevant to you) based on startDate and endDate. Then I display the result in an histogram chart or similar.
If you're looking for a way to fetch or save sleep analysis data with Healthkit, I've written a post a year ago here that can eventually help you.

HKUnit for Sleep Analysis?

I'm need to query HealthKit for HKCategoryTypeIdentifierSleepAnalysis data, but can't find the compatible HKUnit for quantity value. Apple documentation is silent on units for Sleep Analysis. Am hoping someone already knows the answer.
BTW, the iOS Health app shows Hrs & Minutes on the Sleep chart, but the HKUnit reference doesn't include options for such composite units.
In Apples documentation I found this:
By comparing the start and end times of these samples, apps can calculate a number of secondary statistics: the amount of time it took for the user to fall asleep, the percentage of time in bed that the user actually spent sleeping, the number of times the user woke while in bed, and the total amount of time spent both in bed and asleep.
This means that you have to use the startDate and endDate property of your sample to calculate sleep durations.
Sleep samples are instances of HKCategorySample, which is unit-less. You should perform calculations for sleep samples using the startDate and endDate properties on the sample.

How to determine if the iPhone User is Sleeping?

I want to do a sleep analysis for the user in my app.And I think the CoreMotion Framewrok should help.
func queryActivityStartingFromDate(start: NSDate!, toDate end: NSDate!, toQueue queue: NSOperationQueue!, withHandler handler: CMMotionActivityQueryHandler!)
So I use the API above to get the user motion data in the last 7 days.And Now I get a list of CMMotionActivity Object.
And My question is how to calculate the user sleep status from these thousands of CMMotionActivity Object.Is there any algorithms? Or any other way to achieve sleep analysis.
Many Thanks!
CMMotionActivity includes a stationary property which might be useful in your case.
Look for contiguous periods of inactivity, paired with location, timezone & CMDeviceMotion data you should begin to detect patterns in the dataset you have. use statistical variation to define thresholds and fine-tune your results.
Caveat, you will make assumptions which might not be true. Some people sleep in moving vehicles for instance.
I found this pdf useful ftp://ftp.tik.ee.ethz.ch/pub/students/2010-HS/SA-2010-26.pdf

iOS prevent date/time update?

a relatively simple question that I've not been able to find a clear answer to. My app is more complex, but answering this question will suffice.
Suppose you're writing a stopwatch app. When the user taps "start", the app stores the current date and time in startTime:
startTime = [NSDate date];
When the user tapes "stop", the app stores the current date and time in stopTime:
stopTime = [NSDate date];
The duration is calculated by:
duration = [stopTime timeIntervalSinceDate:startTime];
and is displayed with something like:
[durationLabel setText:[NSString stringWithFormat:#"%1.2f", duration]];
The typical durations that my app is timing range from 2 to 50 seconds. I need accuracy to 1/100th of a second (e.g. 2.86 seconds).
I'm assuming that there is some protocol that iOS devices use to keep their clocks accurate (cellular or NTP sources?). My concern is that between starting and stopping the stopwatch, the clock on the iOS device is updated which can result in a shift of the current date/time either ahead or back. If this were to happen, the duration calculated would be inaccurate.
I've seen a few posts relating to timing methods for purposes of improving code efficiency. Some suggest using mach_time.h functions, which I'm not familiar with. It's not obvious to me which is the best approach to use.
Is it possible to disable iOS from updating the date & time? Is mach_absolute_time() unaffected by iOS clock updates?
Many thanks!
Tim
You are correct in thinking that CFAbsoluteTime and its derivatives (NSDate dateand so on) are potentially skewed by network updates on 'real' time. Add that to the fact that NSTimer has an accuracy of 50-100ms and you have a timer that is not suited to the most critical of time-sensitive operations.
The answer to this problem seems to be CACurrentMediaTime.
It is a member of the Core Animation group, but there shouldn't be any problem integrating it into non-animation based applications.
CACurrentMediaTime is a wrapper of mach_absolute_time() and makes sense of the "mach absolute time unit," which from my understanding is no fun to tinker with. mach_absolute_time() is calculated by running a non-network synced timer since the device was last booted.
There is relatively little information on CACurrentMediaTime but here are some sources and further reading:
Apple's sparse documentation of CACurrentMediaTime
Stack Overflow - NSTimer vs CACurrentMediaTime()
http://bendodsonapps.com/weblog/2013/01/29/ca-current-media-time/
http://blog.spacemanlabs.com/2011/09/all-in-the-timing-keeping-track-of-time-passed-on-ios/
http://forum.sparrow-framework.org/topic/accurate-timer
Note: If you do use CACurrentMediaTime, make sure you include and link the QuartzCore.framework
Check out this here. I would say forget about the current time check and use a precision timer since it won't rely on the current time but instead uses an interval.

Resources