簡體   English   中英

如何使用Apple HealthKit獲得每日睡眠時間?

[英]How to get daily sleep duration using Apple HealthKit?

我正在做一個應用程序,它從Apple HealthKit讀取日常步驟和睡眠數據。

對於Steps ,這很容易,因為它是HKQuantityType ,因此我可以在其上應用HKStatisticsOptionCumulativeSum選項。 輸入開始日期,結束日期和日期間隔,就可以了。

- (void)readDailyStepsSince:(NSDate *)date completion:(void (^)(NSArray *results, NSError *error))completion {
    NSDate *today = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *comps = [calendar components:NSCalendarUnitDay|NSCalendarUnitMonth|NSCalendarUnitYear fromDate:date];
    comps.hour = 0;
    comps.minute = 0;
    comps.second = 0;

    NSDate *midnightOfStartDate = [calendar dateFromComponents:comps];
    NSDate *anchorDate = midnightOfStartDate;

    HKQuantityType *stepType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
    HKStatisticsOptions sumOptions = HKStatisticsOptionCumulativeSum;
    NSPredicate *dateRangePred = [HKQuery predicateForSamplesWithStartDate:midnightOfStartDate endDate:today options:HKQueryOptionNone];

    NSDateComponents *interval = [[NSDateComponents alloc] init];
    interval.day = 1;
    HKStatisticsCollectionQuery *query = [[HKStatisticsCollectionQuery alloc] initWithQuantityType:stepType quantitySamplePredicate:dateRangePred options:sumOptions anchorDate:anchorDate intervalComponents:interval];

    query.initialResultsHandler = ^(HKStatisticsCollectionQuery *query, HKStatisticsCollection *result, NSError *error) {

        NSMutableArray *output = [NSMutableArray array];

        // we want "populated" statistics only, so we use result.statistics to iterate
        for (HKStatistics *sample in result.statistics) {
            double steps = [sample.sumQuantity doubleValueForUnit:[HKUnit countUnit]];
            NSDictionary *dict = @{@"date": sample.startDate, @"steps": @(steps)};
            //NSLog(@"[STEP] date:%@ steps:%.0f", s.startDate, steps);
            [output addObject:dict];
        }

        dispatch_async(dispatch_get_main_queue(), ^{
            if (completion != nil) {
                NSLog(@"[STEP] %@", output);
                completion(output, error);
            }
        });
    };

    [self.healthStore executeQuery:query];
}

但是對於睡眠而言 ,並不是那么簡單。 我堅持了很多東西。

  • 首先,與步驟不同,sleep是HKCategoryType 因此,我們不能使用HKStatisticsCollectionQuery對其求和,因為此方法僅接受HKQuantityType
  • 還有2種值的睡眠類型, HKCategoryValueSleepAnalysisInBedHKCategoryValueSleepAnalysisAsleep 我不確定哪個值最適合睡眠時間。 我僅出於簡單起見使用HKCategoryValueSleepAnalysisAsleep
  • 睡眠數據來自HKCategorySample對象數組。 每個都有開始日期和結束日期。 如何有效地合並這些數據,將其修剪到一天之內,並從中獲取每天的睡眠時間(以分鍾為單位)? 我在DateTool窗格中找到了這個DTTimePeriodCollection類,它可以完成此工作,但我還沒有弄清楚。

簡而言之,如果有人知道如何使用Apple HealthKit獲得每日睡眠時間,請告訴我!

我用這個:

@import HealthKit;

@implementation HKHealthStore (AAPLExtensions)


- (void)hkQueryExecute:(void (^)(double, NSError *))completion {
NSCalendar *calendar = [NSCalendar currentCalendar];

NSDate *now = [NSDate date];

NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:now];

NSDate *startDate = [calendar dateFromComponents:components];

NSDate *endDate = [calendar dateByAddingUnit:NSCalendarUnitDay value:1 toDate:startDate options:0];

HKSampleType *sampleType = [HKSampleType categoryTypeForIdentifier:HKCategoryTypeIdentifierSleepAnalysis];
NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startDate endDate:endDate options:HKQueryOptionNone];

HKSampleQuery *query = [[HKSampleQuery alloc] initWithSampleType:sampleType predicate:predicate limit:0 sortDescriptors:nil resultsHandler:^(HKSampleQuery *query, NSArray *results, NSError *error) {
    if (!results) {
        NSLog(@"An error occured fetching the user's sleep duration. In your app, try to handle this gracefully. The error was: %@.", error);
        completion(0, error);
        abort();
    }

        double minutesSleepAggr = 0;
        for (HKCategorySample *sample in results) {

            NSTimeInterval distanceBetweenDates = [sample.endDate timeIntervalSinceDate:sample.startDate];
            double minutesInAnHour = 60;
            double minutesBetweenDates = distanceBetweenDates / minutesInAnHour;

            minutesSleepAggr += minutesBetweenDates;
        }
        completion(minutesSleepAggr, error);
}];

[self executeQuery:query];
}

然后在視圖控制器中:

- (void)updateUsersSleepLabel {
[self.healthStore hkQueryExecute: ^(double minutes, NSError *error) {
    if (minutes == 0) {
        NSLog(@"Either an error occured fetching the user's sleep information or none has been stored yet.");

        dispatch_async(dispatch_get_main_queue(), ^{
            self.sleepDurationValueLabel.text = NSLocalizedString(@"Not available", nil);
        });
    }
    else {

        int hours = (int)minutes / 60;
        int minutesNew = (int)minutes - (hours*60);
        NSLog(@"hours slept: %ld:%ld", (long)hours, (long)minutesNew);

        dispatch_async(dispatch_get_main_queue(), ^{
            self.sleepDurationValueLabel.text = [NSString stringWithFormat:@"%d:%d", hours, minutesNew] ;
        });
    }


}];
}

檢查我是如何做到的,它對我有用以收集睡眠數據

func sleepTime() {
        let healthStore = HKHealthStore()
        // startDate and endDate are NSDate objects
        // first, we define the object type we want
        if let sleepType = HKObjectType.categoryType(forIdentifier: HKCategoryTypeIdentifier.sleepAnalysis) {
            // You may want to use a predicate to filter the data... startDate and endDate are NSDate objects corresponding to the time range that you want to retrieve
            //let predicate = HKQuery.predicateForSamplesWithStartDate(startDate,endDate: endDate ,options: .None)
            // Get the recent data first
            let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false)
            // the block completion to execute
            let query = HKSampleQuery(sampleType: sleepType, predicate: nil, limit: 100000, sortDescriptors: [sortDescriptor]) { (query, tmpResult, error) -> Void in
                if error != nil {
                    // Handle the error in your app gracefully
                    return
                }
                if let result = tmpResult {
                   for item in result {
                        if let sample = item as? HKCategorySample {
                               let startDate = sample.startDate
                               let endDate = sample.endDate
                               print()
                             let sleepTimeForOneDay = sample.endDate.timeIntervalSince(sample.startDate)
                        }
                    }
                }
          }
    }

這給出了入口插槽的陣列。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM