【问题标题】:Apple healthKit REM, Deep, Light sleep analysisApple healthKit REM、深度、轻度睡眠分析
【发布时间】:2022-06-10 23:50:28
【问题描述】:

我正在开发一个需要进行睡眠分析的 IOS 睡眠应用程序。我正在使用 Healthkit 获取睡眠数据,我可以使用以下代码成功获取睡眠分析数据:

func retrieveSleepAnalysis(from startDate: Date?, to endDate: Date? , completion: @escaping ([HKCategorySample], Error?) -> Void) {
guard let sleepType = HKObjectType.categoryType(forIdentifier: .sleepAnalysis) else { return}
        let predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: .strictStartDate)
        let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false)
        let query = HKSampleQuery(sampleType: sleepType, predicate: predicate, limit: 10000, sortDescriptors: [sortDescriptor]) { (query, result, error) in
            if error != nil {
                completion([], error)
                return
            }
            if let result = result {
                let samples = result.compactMap({ $0 as? HKCategorySample})
                completion(samples, nil)
            }
        }
        // finally, we execute our query
        HKHealthStore().execute(query)
    }

我找不到任何用于睡眠 REM 周期、深度睡眠、轻度睡眠等的 healthKit 代码。是否有可能从 healthKit 获取这些数据?如果是,该怎么做? ,如果没有healthKit,如何在IOS应用程序中做到这一点?

【问题讨论】:

    标签: ios swift healthkit


    【解决方案1】:

    您可能会在今年关于“What's New In HealthKit”的 WWDC 演讲中找到您想要的内容

    以下是为所有样本声明谓词的方法:

    // Predicate for all asleep samples (unspecified, core, deep, REM)
    let allAsleepPredicate = HKCategoryValueSleepAnalysis.predicateForSamples(equalTo: .allAsleepValues)
    

    您可以使用它来获取某个范围内的所有样本:

    let healthStore = HKHealthStore()
    let sleepType = HKCategoryType(.sleepAnalysis)
    
    let dateRangePredicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: .strictStartDate)
    let predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [dateRangePredicate, allAsleepPredicate])
    
    let query = HKSampleQuery(sampleType: sleepType, predicate: predicate) { (query, result, error) in
        // handle results
    }
    

    希望有帮助

    【讨论】:

      猜你喜欢
      • 2022-07-08
      • 2014-08-07
      • 1970-01-01
      • 1970-01-01
      • 2017-09-29
      • 2013-03-28
      • 1970-01-01
      • 1970-01-01
      • 2013-04-30
      相关资源
      最近更新 更多