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