HealthKitManager.swift 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  1. import Combine
  2. import CoreData
  3. import Foundation
  4. import HealthKit
  5. import LoopKit
  6. import LoopKitUI
  7. import Swinject
  8. protocol HealthKitManager {
  9. /// Check all needed permissions
  10. /// Return false if one or more permissions are deny or not choosen
  11. var hasGrantedFullWritePermissions: Bool { get }
  12. /// Check availability to save data of BG type to Health store
  13. func hasGlucoseWritePermission() -> Bool
  14. /// Requests user to give permissions on using HealthKit
  15. func requestPermission() async throws -> Bool
  16. /// Checks whether permissions are granted for Trio to write to Health
  17. func checkWriteToHealthPermissions(objectTypeToHealthStore: HKObjectType) -> Bool
  18. /// Save blood glucose to Health store
  19. func uploadGlucose() async
  20. /// Save carbs to Health store
  21. func uploadCarbs() async
  22. /// Save Insulin to Health store
  23. func uploadInsulin() async
  24. /// Delete glucose with syncID
  25. func deleteGlucose(syncID: String) async
  26. /// delete carbs with syncID
  27. func deleteMealData(byID id: String, sampleType: HKSampleType) async
  28. /// delete insulin with syncID
  29. func deleteInsulin(syncID: String) async
  30. }
  31. public enum AppleHealthConfig {
  32. // unwraped HKObjects
  33. static var writePermissions: Set<HKSampleType> {
  34. Set([healthBGObject, healthCarbObject, healthFatObject, healthProteinObject, healthInsulinObject].compactMap { $0 }) }
  35. // link to object in HealthKit
  36. static let healthBGObject = HKObjectType.quantityType(forIdentifier: .bloodGlucose)
  37. static let healthCarbObject = HKObjectType.quantityType(forIdentifier: .dietaryCarbohydrates)
  38. static let healthFatObject = HKObjectType.quantityType(forIdentifier: .dietaryFatTotal)
  39. static let healthProteinObject = HKObjectType.quantityType(forIdentifier: .dietaryProtein)
  40. static let healthInsulinObject = HKObjectType.quantityType(forIdentifier: .insulinDelivery)
  41. // MetaDataKey of Trio data in HealthStore
  42. static let TrioInsulinType = "Trio Insulin Type"
  43. }
  44. final class BaseHealthKitManager: HealthKitManager, Injectable {
  45. @Injected() private var glucoseStorage: GlucoseStorage!
  46. @Injected() private var healthKitStore: HKHealthStore!
  47. @Injected() private var settingsManager: SettingsManager!
  48. @Injected() private var broadcaster: Broadcaster!
  49. @Injected() private var carbsStorage: CarbsStorage!
  50. @Injected() private var pumpHistoryStorage: PumpHistoryStorage!
  51. @Injected() private var deviceDataManager: DeviceDataManager!
  52. private var backgroundContext = CoreDataStack.shared.newTaskContext()
  53. private var coreDataPublisher: AnyPublisher<Set<NSManagedObject>, Never>?
  54. private var subscriptions = Set<AnyCancellable>()
  55. var isAvailableOnCurrentDevice: Bool {
  56. HKHealthStore.isHealthDataAvailable()
  57. }
  58. init(resolver: Resolver) {
  59. injectServices(resolver)
  60. coreDataPublisher =
  61. changedObjectsOnManagedObjectContextDidSavePublisher()
  62. .receive(on: DispatchQueue.global(qos: .background))
  63. .share()
  64. .eraseToAnyPublisher()
  65. glucoseStorage.updatePublisher
  66. .receive(on: DispatchQueue.global(qos: .background))
  67. .sink { [weak self] _ in
  68. guard let self = self else { return }
  69. Task {
  70. await self.uploadGlucose()
  71. }
  72. }
  73. .store(in: &subscriptions)
  74. registerHandlers()
  75. guard isAvailableOnCurrentDevice,
  76. AppleHealthConfig.healthBGObject != nil else { return }
  77. debug(.service, "HealthKitManager did create")
  78. }
  79. private func registerHandlers() {
  80. coreDataPublisher?.filterByEntityName("PumpEventStored").sink { [weak self] _ in
  81. guard let self = self else { return }
  82. Task { [weak self] in
  83. guard let self = self else { return }
  84. await self.uploadInsulin()
  85. }
  86. }.store(in: &subscriptions)
  87. coreDataPublisher?.filterByEntityName("CarbEntryStored").sink { [weak self] _ in
  88. guard let self = self else { return }
  89. Task { [weak self] in
  90. guard let self = self else { return }
  91. await self.uploadCarbs()
  92. }
  93. }.store(in: &subscriptions)
  94. // This works only for manual Glucose
  95. coreDataPublisher?.filterByEntityName("GlucoseStored").sink { [weak self] _ in
  96. guard let self = self else { return }
  97. Task { [weak self] in
  98. guard let self = self else { return }
  99. await self.uploadGlucose()
  100. }
  101. }.store(in: &subscriptions)
  102. }
  103. func checkWriteToHealthPermissions(objectTypeToHealthStore: HKObjectType) -> Bool {
  104. healthKitStore.authorizationStatus(for: objectTypeToHealthStore) == .sharingAuthorized
  105. }
  106. var hasGrantedFullWritePermissions: Bool {
  107. Set(AppleHealthConfig.writePermissions.map { healthKitStore.authorizationStatus(for: $0) })
  108. .intersection([.sharingDenied, .notDetermined])
  109. .isEmpty
  110. }
  111. func hasGlucoseWritePermission() -> Bool {
  112. AppleHealthConfig.healthBGObject.map { checkWriteToHealthPermissions(objectTypeToHealthStore: $0) } ?? false
  113. }
  114. func requestPermission() async throws -> Bool {
  115. guard isAvailableOnCurrentDevice else {
  116. throw HKError.notAvailableOnCurrentDevice
  117. }
  118. return try await withCheckedThrowingContinuation { continuation in
  119. healthKitStore.requestAuthorization(
  120. toShare: AppleHealthConfig.writePermissions,
  121. read: nil
  122. ) { status, error in
  123. if let error = error {
  124. continuation.resume(throwing: error)
  125. } else {
  126. continuation.resume(returning: status)
  127. }
  128. }
  129. }
  130. }
  131. // Glucose Upload
  132. func uploadGlucose() async {
  133. await uploadGlucose(glucoseStorage.getGlucoseNotYetUploadedToHealth())
  134. await uploadGlucose(glucoseStorage.getManualGlucoseNotYetUploadedToHealth())
  135. }
  136. func uploadGlucose(_ glucose: [BloodGlucose]) async {
  137. guard settingsManager.settings.useAppleHealth,
  138. let sampleType = AppleHealthConfig.healthBGObject,
  139. checkWriteToHealthPermissions(objectTypeToHealthStore: sampleType),
  140. glucose.isNotEmpty
  141. else { return }
  142. do {
  143. // Create HealthKit samples from all the passed glucose values
  144. let glucoseSamples = glucose.compactMap { glucoseSample -> HKQuantitySample? in
  145. guard let glucoseValue = glucoseSample.glucose else { return nil }
  146. return HKQuantitySample(
  147. type: sampleType,
  148. quantity: HKQuantity(unit: .milligramsPerDeciliter, doubleValue: Double(glucoseValue)),
  149. start: glucoseSample.dateString,
  150. end: glucoseSample.dateString,
  151. metadata: [
  152. HKMetadataKeyExternalUUID: glucoseSample.id,
  153. HKMetadataKeySyncIdentifier: glucoseSample.id,
  154. HKMetadataKeySyncVersion: 1,
  155. AppleHealthConfig.TrioInsulinType: deviceDataManager?.pumpManager?.status.insulinType?.title ?? ""
  156. ]
  157. )
  158. }
  159. guard glucoseSamples.isNotEmpty else {
  160. debug(.service, "No glucose samples available for upload.")
  161. return
  162. }
  163. // Attempt to save the blood glucose samples to Apple Health
  164. try await healthKitStore.save(glucoseSamples)
  165. debug(.service, "Successfully stored \(glucoseSamples.count) blood glucose samples in HealthKit.")
  166. // After successful upload, update the isUploadedToHealth flag in Core Data
  167. await updateGlucoseAsUploaded(glucose)
  168. } catch {
  169. debug(.service, "Failed to upload glucose samples to HealthKit: \(error.localizedDescription)")
  170. }
  171. }
  172. private func updateGlucoseAsUploaded(_ glucose: [BloodGlucose]) async {
  173. await backgroundContext.perform {
  174. let ids = glucose.map(\.id) as NSArray
  175. let fetchRequest: NSFetchRequest<GlucoseStored> = GlucoseStored.fetchRequest()
  176. fetchRequest.predicate = NSPredicate(format: "id IN %@", ids)
  177. do {
  178. let results = try self.backgroundContext.fetch(fetchRequest)
  179. for result in results {
  180. result.isUploadedToHealth = true
  181. }
  182. guard self.backgroundContext.hasChanges else { return }
  183. try self.backgroundContext.save()
  184. } catch let error as NSError {
  185. debugPrint(
  186. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to update isUploadedToHealth: \(error.userInfo)"
  187. )
  188. }
  189. }
  190. }
  191. // Carbs Upload
  192. func uploadCarbs() async {
  193. await uploadCarbs(carbsStorage.getCarbsNotYetUploadedToHealth())
  194. }
  195. func uploadCarbs(_ carbs: [CarbsEntry]) async {
  196. guard settingsManager.settings.useAppleHealth,
  197. let carbSampleType = AppleHealthConfig.healthCarbObject,
  198. let fatSampleType = AppleHealthConfig.healthFatObject,
  199. let proteinSampleType = AppleHealthConfig.healthProteinObject,
  200. checkWriteToHealthPermissions(objectTypeToHealthStore: carbSampleType),
  201. carbs.isNotEmpty
  202. else { return }
  203. do {
  204. var samples: [HKQuantitySample] = []
  205. // Create HealthKit samples for carbs, fat, and protein
  206. for allSamples in carbs {
  207. guard let id = allSamples.id else { continue }
  208. let fpuID = allSamples.fpuID ?? id
  209. let startDate = allSamples.actualDate ?? Date()
  210. // Carbs Sample
  211. let carbValue = allSamples.carbs
  212. let carbSample = HKQuantitySample(
  213. type: carbSampleType,
  214. quantity: HKQuantity(unit: .gram(), doubleValue: Double(carbValue)),
  215. start: startDate,
  216. end: startDate,
  217. metadata: [
  218. HKMetadataKeyExternalUUID: id,
  219. HKMetadataKeySyncIdentifier: id,
  220. HKMetadataKeySyncVersion: 1
  221. ]
  222. )
  223. samples.append(carbSample)
  224. // Fat Sample (if available)
  225. if let fatValue = allSamples.fat {
  226. let fatSample = HKQuantitySample(
  227. type: fatSampleType,
  228. quantity: HKQuantity(unit: .gram(), doubleValue: Double(fatValue)),
  229. start: startDate,
  230. end: startDate,
  231. metadata: [
  232. HKMetadataKeyExternalUUID: fpuID,
  233. HKMetadataKeySyncIdentifier: fpuID,
  234. HKMetadataKeySyncVersion: 1
  235. ]
  236. )
  237. samples.append(fatSample)
  238. }
  239. // Protein Sample (if available)
  240. if let proteinValue = allSamples.protein {
  241. let proteinSample = HKQuantitySample(
  242. type: proteinSampleType,
  243. quantity: HKQuantity(unit: .gram(), doubleValue: Double(proteinValue)),
  244. start: startDate,
  245. end: startDate,
  246. metadata: [
  247. HKMetadataKeyExternalUUID: fpuID,
  248. HKMetadataKeySyncIdentifier: fpuID,
  249. HKMetadataKeySyncVersion: 1
  250. ]
  251. )
  252. samples.append(proteinSample)
  253. }
  254. }
  255. // Attempt to save the samples to Apple Health
  256. guard samples.isNotEmpty else {
  257. debug(.service, "No samples available for upload.")
  258. return
  259. }
  260. try await healthKitStore.save(samples)
  261. debug(.service, "Successfully stored \(samples.count) carb samples in HealthKit.")
  262. // After successful upload, update the isUploadedToHealth flag in Core Data
  263. await updateCarbsAsUploaded(carbs)
  264. } catch {
  265. debug(.service, "Failed to upload carb samples to HealthKit: \(error.localizedDescription)")
  266. }
  267. }
  268. private func updateCarbsAsUploaded(_ carbs: [CarbsEntry]) async {
  269. await backgroundContext.perform {
  270. let ids = carbs.map(\.id) as NSArray
  271. let fetchRequest: NSFetchRequest<CarbEntryStored> = CarbEntryStored.fetchRequest()
  272. fetchRequest.predicate = NSPredicate(format: "id IN %@", ids)
  273. do {
  274. let results = try self.backgroundContext.fetch(fetchRequest)
  275. for result in results {
  276. result.isUploadedToHealth = true
  277. }
  278. guard self.backgroundContext.hasChanges else { return }
  279. try self.backgroundContext.save()
  280. } catch let error as NSError {
  281. debugPrint(
  282. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to update isUploadedToHealth: \(error.userInfo)"
  283. )
  284. }
  285. }
  286. }
  287. // Insulin Upload
  288. func uploadInsulin() async {
  289. await uploadInsulin(pumpHistoryStorage.getPumpHistoryNotYetUploadedToHealth())
  290. }
  291. func uploadInsulin(_ insulinEvents: [PumpHistoryEvent]) async {
  292. guard settingsManager.settings.useAppleHealth,
  293. let sampleType = AppleHealthConfig.healthInsulinObject,
  294. checkWriteToHealthPermissions(objectTypeToHealthStore: sampleType),
  295. insulinEvents.isNotEmpty else { return }
  296. // Fetch existing temp basal entries from Core Data for the last 24 hours
  297. let fetchedInsulinEntries = await CoreDataStack.shared.fetchEntitiesAsync(
  298. ofType: PumpEventStored.self,
  299. onContext: backgroundContext,
  300. predicate: NSCompoundPredicate(andPredicateWithSubpredicates: [
  301. NSPredicate.pumpHistoryLast24h,
  302. NSPredicate(format: "tempBasal != nil")
  303. ]),
  304. key: "timestamp",
  305. ascending: true,
  306. batchSize: 50
  307. )
  308. var insulinSamples: [HKQuantitySample] = []
  309. await backgroundContext.perform {
  310. guard let existingTempBasalEntries = fetchedInsulinEntries as? [PumpEventStored] else { return }
  311. for event in insulinEvents {
  312. switch event.type {
  313. case .bolus:
  314. // For bolus events, create a HealthKit sample directly
  315. if let sample = self.createSample(for: event, sampleType: sampleType) {
  316. debug(.service, "Created HealthKit sample for bolus entry: \(sample)")
  317. insulinSamples.append(sample)
  318. }
  319. case .tempBasal:
  320. // For temp basal events, process them and adjust overlapping durations if necessary
  321. guard let duration = event.duration, let amount = event.amount else { continue }
  322. let value = (Decimal(duration) / 60.0) * amount
  323. let valueRounded = self.deviceDataManager?.pumpManager?
  324. .roundToSupportedBolusVolume(units: Double(value)) ?? Double(value)
  325. // Use binary search for efficient lookup of matching entry
  326. if let matchingIndex = self.binarySearch(entries: existingTempBasalEntries, timestamp: event.timestamp) {
  327. let predecessorIndex = matchingIndex - 1
  328. if predecessorIndex >= 0 {
  329. let predecessorEntry = existingTempBasalEntries[predecessorIndex]
  330. if let adjustedSample = self.processPredecessorEntry(
  331. predecessorEntry,
  332. nextEventTimestamp: event.timestamp,
  333. sampleType: sampleType
  334. ) {
  335. insulinSamples.append(adjustedSample)
  336. }
  337. }
  338. let newEvent = PumpHistoryEvent(
  339. id: event.id,
  340. type: .tempBasal,
  341. timestamp: event.timestamp,
  342. amount: Decimal(valueRounded),
  343. duration: event.duration
  344. )
  345. if let sample = self.createSample(for: newEvent, sampleType: sampleType) {
  346. debug(.service, "Created HealthKit sample for initial temp basal entry: \(sample)")
  347. insulinSamples.append(sample)
  348. }
  349. }
  350. default:
  351. break
  352. }
  353. }
  354. }
  355. do {
  356. guard insulinSamples.isNotEmpty else {
  357. debug(.service, "No insulin samples available for upload.")
  358. return
  359. }
  360. try await healthKitStore.save(insulinSamples)
  361. debug(.service, "Successfully stored \(insulinSamples.count) insulin samples in HealthKit.")
  362. await updateInsulinAsUploaded(insulinEvents)
  363. } catch {
  364. debug(.service, "Failed to upload insulin samples to HealthKit: \(error.localizedDescription)")
  365. }
  366. }
  367. // Helper function to perform binary search on the sorted entries by timestamp
  368. private func binarySearch(entries: [PumpEventStored], timestamp: Date) -> Int? {
  369. var lowerBound = 0
  370. var upperBound = entries.count - 1
  371. while lowerBound <= upperBound {
  372. let midIndex = (lowerBound + upperBound) / 2
  373. guard let midTimestamp = entries[midIndex].timestamp else { return nil }
  374. if midTimestamp == timestamp {
  375. return midIndex
  376. } else if midTimestamp < timestamp {
  377. lowerBound = midIndex + 1
  378. } else {
  379. upperBound = midIndex - 1
  380. }
  381. }
  382. return nil
  383. }
  384. // Helper function to create a HealthKit sample from a PumpHistoryEvent
  385. private func createSample(
  386. for event: PumpHistoryEvent,
  387. sampleType: HKQuantityType
  388. ) -> HKQuantitySample? {
  389. // Ensure the event has a valid insulin amount
  390. guard let insulinValue = event.amount else { return nil }
  391. // Determine the insulin delivery reason based on the event type
  392. let deliveryReason: HKInsulinDeliveryReason
  393. switch event.type {
  394. case .bolus:
  395. deliveryReason = .bolus
  396. case .tempBasal:
  397. deliveryReason = .basal
  398. default:
  399. return nil
  400. }
  401. // Calculate the end date based on the event duration
  402. let endDate = event.timestamp.addingTimeInterval(TimeInterval(minutes: Double(event.duration ?? 0)))
  403. // Create the HealthKit quantity sample with the appropriate metadata
  404. let sample = HKQuantitySample(
  405. type: sampleType,
  406. quantity: HKQuantity(unit: .internationalUnit(), doubleValue: Double(insulinValue)),
  407. start: event.timestamp,
  408. end: endDate,
  409. metadata: [
  410. HKMetadataKeyExternalUUID: event.id,
  411. HKMetadataKeySyncIdentifier: event.id,
  412. HKMetadataKeySyncVersion: 1,
  413. HKMetadataKeyInsulinDeliveryReason: deliveryReason.rawValue,
  414. AppleHealthConfig.TrioInsulinType: deviceDataManager?.pumpManager?.status.insulinType?.title ?? ""
  415. ]
  416. )
  417. return sample
  418. }
  419. // Helper function to process a predecessor temp basal entry and adjust overlapping durations
  420. private func processPredecessorEntry(
  421. _ predecessorEntry: PumpEventStored,
  422. nextEventTimestamp: Date,
  423. sampleType: HKQuantityType
  424. ) -> HKQuantitySample? {
  425. // Ensure the predecessor entry has the necessary data
  426. guard let predecessorTimestamp = predecessorEntry.timestamp,
  427. let predecessorEntryId = predecessorEntry.id else { return nil }
  428. // Calculate the original end date of the predecessor temp basal
  429. let predecessorDurationMinutes = predecessorEntry.tempBasal?.duration ?? 0
  430. let predecessorEndDate = predecessorTimestamp.addingTimeInterval(TimeInterval(predecessorDurationMinutes * 60))
  431. // Check if the predecessor temp basal overlaps with the next event
  432. if predecessorEndDate > nextEventTimestamp {
  433. // Adjust the end date to the start of the next event to prevent overlap
  434. let adjustedEndDate = nextEventTimestamp
  435. // Precise duration in seconds
  436. let adjustedDuration = adjustedEndDate.timeIntervalSince(predecessorTimestamp)
  437. // Precise duration in hours
  438. let adjustedDurationHours = adjustedDuration / 3600
  439. // Calculate the insulin rate and adjusted delivered units
  440. let predecessorEntryRate = predecessorEntry.tempBasal?.rate?.doubleValue ?? 0
  441. let adjustedDeliveredUnits = adjustedDurationHours * predecessorEntryRate
  442. let adjustedDeliveredUnitsRounded = deviceDataManager?.pumpManager?
  443. .roundToSupportedBolusVolume(units: adjustedDeliveredUnits) ?? adjustedDeliveredUnits
  444. // Create the HealthKit quantity sample with the appropriate metadata
  445. // Intentionally do it here manually and do not use `createSample()` to handle utmost precise `end`.
  446. let sample = HKQuantitySample(
  447. type: sampleType,
  448. quantity: HKQuantity(unit: .internationalUnit(), doubleValue: Double(adjustedDeliveredUnitsRounded)),
  449. start: predecessorTimestamp,
  450. end: adjustedEndDate,
  451. metadata: [
  452. HKMetadataKeyExternalUUID: predecessorEntryId,
  453. HKMetadataKeySyncIdentifier: predecessorEntryId,
  454. HKMetadataKeySyncVersion: 2, // set the version # to 2, as we update an entry. initial version is 1.
  455. HKMetadataKeyInsulinDeliveryReason: HKInsulinDeliveryReason.basal.rawValue,
  456. AppleHealthConfig.TrioInsulinType: deviceDataManager?.pumpManager?.status.insulinType?.title ?? ""
  457. ]
  458. )
  459. debug(.service, "Created HealthKit sample for adjusted temp basal entry: \(sample)")
  460. // Create and return the HealthKit sample for the adjusted event
  461. return sample
  462. }
  463. // If there is no overlap, no adjustment is needed
  464. return nil
  465. }
  466. private func updateInsulinAsUploaded(_ insulin: [PumpHistoryEvent]) async {
  467. await backgroundContext.perform {
  468. let ids = insulin.map(\.id) as NSArray
  469. let fetchRequest: NSFetchRequest<PumpEventStored> = PumpEventStored.fetchRequest()
  470. fetchRequest.predicate = NSPredicate(format: "id IN %@", ids)
  471. do {
  472. let results = try self.backgroundContext.fetch(fetchRequest)
  473. for result in results {
  474. result.isUploadedToHealth = true
  475. }
  476. guard self.backgroundContext.hasChanges else { return }
  477. try self.backgroundContext.save()
  478. } catch let error as NSError {
  479. debugPrint(
  480. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to update isUploadedToHealth: \(error.userInfo)"
  481. )
  482. }
  483. }
  484. }
  485. // Delete Glucose/Carbs/Insulin
  486. func deleteGlucose(syncID: String) async {
  487. guard settingsManager.settings.useAppleHealth,
  488. let sampleType = AppleHealthConfig.healthBGObject,
  489. checkWriteToHealthPermissions(objectTypeToHealthStore: sampleType)
  490. else { return }
  491. let predicate = HKQuery.predicateForObjects(
  492. withMetadataKey: HKMetadataKeySyncIdentifier,
  493. operatorType: .equalTo,
  494. value: syncID
  495. )
  496. do {
  497. try await deleteObjects(of: sampleType, predicate: predicate)
  498. debug(.service, "Successfully deleted glucose sample with syncID: \(syncID)")
  499. } catch {
  500. warning(.service, "Failed to delete glucose sample with syncID: \(syncID)", error: error)
  501. }
  502. }
  503. func deleteMealData(byID id: String, sampleType: HKSampleType) async {
  504. guard settingsManager.settings.useAppleHealth else { return }
  505. let predicate = HKQuery.predicateForObjects(
  506. withMetadataKey: HKMetadataKeySyncIdentifier,
  507. operatorType: .equalTo,
  508. value: id
  509. )
  510. do {
  511. try await deleteObjects(of: sampleType, predicate: predicate)
  512. debug(.service, "Successfully deleted \(sampleType) with syncID: \(id)")
  513. } catch {
  514. warning(.service, "Failed to delete carbs sample with syncID: \(id)", error: error)
  515. }
  516. }
  517. func deleteInsulin(syncID: String) async {
  518. guard settingsManager.settings.useAppleHealth,
  519. let sampleType = AppleHealthConfig.healthInsulinObject,
  520. checkWriteToHealthPermissions(objectTypeToHealthStore: sampleType)
  521. else {
  522. debug(.service, "HealthKit permissions are not available for insulin deletion.")
  523. return
  524. }
  525. let predicate = HKQuery.predicateForObjects(
  526. withMetadataKey: HKMetadataKeySyncIdentifier,
  527. operatorType: .equalTo,
  528. value: syncID
  529. )
  530. do {
  531. try await deleteObjects(of: sampleType, predicate: predicate)
  532. debug(.service, "Successfully deleted insulin sample with syncID: \(syncID)")
  533. } catch {
  534. warning(.service, "Failed to delete insulin sample with syncID: \(syncID)", error: error)
  535. }
  536. }
  537. private func deleteObjects(of sampleType: HKSampleType, predicate: NSPredicate) async throws {
  538. try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
  539. healthKitStore.deleteObjects(of: sampleType, predicate: predicate) { success, _, error in
  540. if let error = error {
  541. continuation.resume(throwing: error)
  542. } else if success {
  543. continuation.resume(returning: ())
  544. }
  545. }
  546. }
  547. }
  548. }
  549. enum HealthKitPermissionRequestStatus {
  550. case needRequest
  551. case didRequest
  552. }
  553. enum HKError: Error {
  554. // HealthKit work only iPhone (not on iPad)
  555. case notAvailableOnCurrentDevice
  556. // Some data can be not available on current iOS-device
  557. case dataNotAvailable
  558. }
  559. private struct InsulinBolus {
  560. var id: String
  561. var amount: Decimal
  562. var date: Date
  563. }
  564. private struct InsulinBasal {
  565. var id: String
  566. var amount: Decimal
  567. var startDelivery: Date
  568. var endDelivery: Date
  569. }