HealthKitManager.swift 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  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(_ insulin: [PumpHistoryEvent]) async {
  292. guard settingsManager.settings.useAppleHealth,
  293. let sampleType = AppleHealthConfig.healthInsulinObject,
  294. checkWriteToHealthPermissions(objectTypeToHealthStore: sampleType),
  295. insulin.isNotEmpty
  296. else { return }
  297. // Fetch existing temp basal entries from Core Data for the last 24 hours
  298. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  299. ofType: PumpEventStored.self,
  300. onContext: backgroundContext,
  301. predicate: NSCompoundPredicate(andPredicateWithSubpredicates: [
  302. NSPredicate.pumpHistoryLast24h,
  303. NSPredicate(format: "tempBasal != nil")
  304. ]),
  305. key: "timestamp",
  306. ascending: true,
  307. batchSize: 50
  308. )
  309. // Perform the data processing on the background context
  310. await backgroundContext.perform {
  311. guard let existingTempBasalEntries = results as? [PumpEventStored] else { return }
  312. let insulinSamples: [HKQuantitySample] = insulin.reduce([]) { result, event in
  313. var result = result
  314. switch event.type {
  315. case .bolus:
  316. // For bolus events, create a HealthKit sample directly
  317. if let sample = self.createSample(for: event, sampleType: sampleType) {
  318. debug(.service, "Created HealthKit sample for bolus entry: \(sample)")
  319. result.append(sample)
  320. }
  321. case .tempBasal:
  322. // For temp basal events, process them and adjust overlapping durations if necessary
  323. guard let duration = event.duration, let amount = event.amount else { return result }
  324. let value = (Decimal(duration) / 60.0) * amount
  325. let valueRounded = self.deviceDataManager?.pumpManager?
  326. .roundToSupportedBolusVolume(units: Double(value)) ?? Double(value)
  327. // Process and append temp basal event
  328. let newEvent = PumpHistoryEvent(
  329. id: event.id,
  330. type: .tempBasal,
  331. timestamp: event.timestamp,
  332. amount: Decimal(valueRounded),
  333. duration: event.duration
  334. )
  335. if let sample = self.createSample(for: newEvent, sampleType: sampleType) {
  336. debug(.service, "Created HealthKit sample for temp basal entry: \(sample)")
  337. result.append(sample)
  338. }
  339. default:
  340. break
  341. }
  342. return result
  343. }
  344. // Save the processed insulin samples to HealthKit
  345. Task {
  346. do {
  347. guard insulinSamples.isNotEmpty else {
  348. debug(.service, "No insulin samples available for upload.")
  349. return
  350. }
  351. try await self.healthKitStore.save(insulinSamples)
  352. debug(.service, "Successfully stored \(insulinSamples.count) insulin samples in HealthKit.")
  353. // Mark the insulin events as uploaded
  354. await self.updateInsulinAsUploaded(insulin)
  355. } catch {
  356. debug(.service, "Failed to upload insulin samples to HealthKit: \(error.localizedDescription)")
  357. }
  358. }
  359. }
  360. }
  361. // Helper function to create a HealthKit sample from a PumpHistoryEvent
  362. private func createSample(
  363. for event: PumpHistoryEvent,
  364. sampleType: HKQuantityType
  365. ) -> HKQuantitySample? {
  366. // Ensure the event has a valid insulin amount
  367. guard let insulinValue = event.amount else { return nil }
  368. // Determine the insulin delivery reason based on the event type
  369. let deliveryReason: HKInsulinDeliveryReason
  370. switch event.type {
  371. case .bolus:
  372. deliveryReason = .bolus
  373. case .tempBasal:
  374. deliveryReason = .basal
  375. default:
  376. return nil
  377. }
  378. // Calculate the end date based on the event duration
  379. let endDate = event.timestamp.addingTimeInterval(TimeInterval(minutes: Double(event.duration ?? 0)))
  380. // Create the HealthKit quantity sample with the appropriate metadata
  381. let sample = HKQuantitySample(
  382. type: sampleType,
  383. quantity: HKQuantity(unit: .internationalUnit(), doubleValue: Double(insulinValue)),
  384. start: event.timestamp,
  385. end: endDate,
  386. metadata: [
  387. HKMetadataKeyExternalUUID: event.id,
  388. HKMetadataKeySyncIdentifier: event.id,
  389. HKMetadataKeySyncVersion: 1,
  390. HKMetadataKeyInsulinDeliveryReason: deliveryReason.rawValue,
  391. AppleHealthConfig.TrioInsulinType: deviceDataManager?.pumpManager?.status.insulinType?.title ?? ""
  392. ]
  393. )
  394. return sample
  395. }
  396. // Helper function to process a predecessor temp basal entry and adjust overlapping durations
  397. private func processPredecessorEntry(
  398. _ predecessorEntry: PumpEventStored,
  399. nextEventTimestamp: Date,
  400. sampleType: HKQuantityType
  401. ) -> HKQuantitySample? {
  402. // Ensure the predecessor entry has the necessary data
  403. guard let predecessorTimestamp = predecessorEntry.timestamp,
  404. let predecessorEntryId = predecessorEntry.id else { return nil }
  405. // Calculate the original end date of the predecessor temp basal
  406. let predecessorDurationMinutes = predecessorEntry.tempBasal?.duration ?? 0
  407. let predecessorEndDate = predecessorTimestamp.addingTimeInterval(TimeInterval(predecessorDurationMinutes * 60))
  408. // Check if the predecessor temp basal overlaps with the next event
  409. if predecessorEndDate > nextEventTimestamp {
  410. // Adjust the end date to the start of the next event to prevent overlap
  411. let adjustedEndDate = nextEventTimestamp
  412. // Precise duration in seconds
  413. let adjustedDuration = adjustedEndDate.timeIntervalSince(predecessorTimestamp)
  414. // Precise duration in hours
  415. let adjustedDurationHours = adjustedDuration / 3600
  416. // Calculate the insulin rate and adjusted delivered units
  417. let predecessorEntryRate = predecessorEntry.tempBasal?.rate?.doubleValue ?? 0
  418. let adjustedDeliveredUnits = adjustedDurationHours * predecessorEntryRate
  419. let adjustedDeliveredUnitsRounded = deviceDataManager?.pumpManager?
  420. .roundToSupportedBolusVolume(units: adjustedDeliveredUnits) ?? adjustedDeliveredUnits
  421. // Create the HealthKit quantity sample with the appropriate metadata
  422. // Intentionally do it here manually and do not use `createSample()` to handle utmost precise `end`.
  423. let sample = HKQuantitySample(
  424. type: sampleType,
  425. quantity: HKQuantity(unit: .internationalUnit(), doubleValue: Double(adjustedDeliveredUnitsRounded)),
  426. start: predecessorTimestamp,
  427. end: adjustedEndDate,
  428. metadata: [
  429. HKMetadataKeyExternalUUID: predecessorEntryId,
  430. HKMetadataKeySyncIdentifier: predecessorEntryId,
  431. HKMetadataKeySyncVersion: 2, // set the version # to 2, as we update an entry. initial version is 1.
  432. HKMetadataKeyInsulinDeliveryReason: HKInsulinDeliveryReason.basal.rawValue,
  433. AppleHealthConfig.TrioInsulinType: deviceDataManager?.pumpManager?.status.insulinType?.title ?? ""
  434. ]
  435. )
  436. debug(.service, "Created HealthKit sample for adjusted temp basal entry: \(sample)")
  437. // Create and return the HealthKit sample for the adjusted event
  438. return sample
  439. }
  440. // If there is no overlap, no adjustment is needed
  441. return nil
  442. }
  443. private func updateInsulinAsUploaded(_ insulin: [PumpHistoryEvent]) async {
  444. await backgroundContext.perform {
  445. let ids = insulin.map(\.id) as NSArray
  446. let fetchRequest: NSFetchRequest<PumpEventStored> = PumpEventStored.fetchRequest()
  447. fetchRequest.predicate = NSPredicate(format: "id IN %@", ids)
  448. do {
  449. let results = try self.backgroundContext.fetch(fetchRequest)
  450. for result in results {
  451. result.isUploadedToHealth = true
  452. }
  453. guard self.backgroundContext.hasChanges else { return }
  454. try self.backgroundContext.save()
  455. } catch let error as NSError {
  456. debugPrint(
  457. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to update isUploadedToHealth: \(error.userInfo)"
  458. )
  459. }
  460. }
  461. }
  462. // Delete Glucose/Carbs/Insulin
  463. func deleteGlucose(syncID: String) async {
  464. guard settingsManager.settings.useAppleHealth,
  465. let sampleType = AppleHealthConfig.healthBGObject,
  466. checkWriteToHealthPermissions(objectTypeToHealthStore: sampleType)
  467. else { return }
  468. let predicate = HKQuery.predicateForObjects(
  469. withMetadataKey: HKMetadataKeySyncIdentifier,
  470. operatorType: .equalTo,
  471. value: syncID
  472. )
  473. do {
  474. try await deleteObjects(of: sampleType, predicate: predicate)
  475. debug(.service, "Successfully deleted glucose sample with syncID: \(syncID)")
  476. } catch {
  477. warning(.service, "Failed to delete glucose sample with syncID: \(syncID)", error: error)
  478. }
  479. }
  480. func deleteMealData(byID id: String, sampleType: HKSampleType) async {
  481. guard settingsManager.settings.useAppleHealth else { return }
  482. let predicate = HKQuery.predicateForObjects(
  483. withMetadataKey: HKMetadataKeySyncIdentifier,
  484. operatorType: .equalTo,
  485. value: id
  486. )
  487. do {
  488. try await deleteObjects(of: sampleType, predicate: predicate)
  489. debug(.service, "Successfully deleted \(sampleType) with syncID: \(id)")
  490. } catch {
  491. warning(.service, "Failed to delete carbs sample with syncID: \(id)", error: error)
  492. }
  493. }
  494. func deleteInsulin(syncID: String) async {
  495. guard settingsManager.settings.useAppleHealth,
  496. let sampleType = AppleHealthConfig.healthInsulinObject,
  497. checkWriteToHealthPermissions(objectTypeToHealthStore: sampleType)
  498. else {
  499. debug(.service, "HealthKit permissions are not available for insulin deletion.")
  500. return
  501. }
  502. let predicate = HKQuery.predicateForObjects(
  503. withMetadataKey: HKMetadataKeySyncIdentifier,
  504. operatorType: .equalTo,
  505. value: syncID
  506. )
  507. do {
  508. try await deleteObjects(of: sampleType, predicate: predicate)
  509. debug(.service, "Successfully deleted insulin sample with syncID: \(syncID)")
  510. } catch {
  511. warning(.service, "Failed to delete insulin sample with syncID: \(syncID)", error: error)
  512. }
  513. }
  514. private func deleteObjects(of sampleType: HKSampleType, predicate: NSPredicate) async throws {
  515. try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
  516. healthKitStore.deleteObjects(of: sampleType, predicate: predicate) { success, _, error in
  517. if let error = error {
  518. continuation.resume(throwing: error)
  519. } else if success {
  520. continuation.resume(returning: ())
  521. }
  522. }
  523. }
  524. }
  525. }
  526. enum HealthKitPermissionRequestStatus {
  527. case needRequest
  528. case didRequest
  529. }
  530. enum HKError: Error {
  531. // HealthKit work only iPhone (not on iPad)
  532. case notAvailableOnCurrentDevice
  533. // Some data can be not available on current iOS-device
  534. case dataNotAvailable
  535. }
  536. private struct InsulinBolus {
  537. var id: String
  538. var amount: Decimal
  539. var date: Date
  540. }
  541. private struct InsulinBasal {
  542. var id: String
  543. var amount: Decimal
  544. var startDelivery: Date
  545. var endDelivery: Date
  546. }