I have issue to request Authorization and get the total sleep hours from HealthKit
func requestAuthorization(completion: @escaping (Bool) -> Void) { let stepType = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)! let heartRate = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate)! let spo2 = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.respiratoryRate)! let sleepHours = HKObjectType.categoryType(forIdentifier: .sleepAnalysis) let setType = Set(arrayLiteral: sleep_type_t) //error cannot find 'sleepType' in scope **** guard let healthStore = self.healthStore else { return completion(false) } healthStore.requestAuthorization(toShare: [], read: [stepType,heartRate,spo2,sleepHours]) { (success, error) in completion(success) } }
func getSleepHours(completion: @escaping (_ sleepHours: String?) -> Void) { let sampleType = HKObjectType.categoryType(forIdentifier: HKCategoryTypeIdentifier.sleepAnalysis)! // Get all samples from the last 24 hours let endDate = Date() let startDate = endDate.addingTimeInterval(-1.0 * 60.0 * 60.0 * 24.0) let predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: []) let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false) // Sleep query let sleepQuery = HKSampleQuery(sampleType: sampleType,predicate: predicate,limit: 0,sortDescriptors: [sortDescriptor]) { (query, results, error) -> Void in if error != nil {return} // Sum the sleep time var minutesSleepAggr = 0.0 if let result = results { for item in result { if let sample = item as? HKCategorySample { if sample.value == HKCategoryValueSleepAnalysis.asleep.rawValue && sample.startDate >= startDate { let sleepTime = sample.endDate.timeIntervalSince(sample.startDate) let minutesInAnHour = 60.0 let minutesBetweenDates = sleepTime / minutesInAnHour minutesSleepAggr += minutesBetweenDates } } } let sleepHours = Double(String(format: "%.1f", minutesSleepAggr / 60))! let sleepHours2 = "(sleepHours)" completion(sleepHours2) print("*** SLEEP HOURS: (String(describing: sleepHours))") } } healthStore?.execute(sleepQuery) }