HealthKitManager.swift 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672
  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 (only if value is greater than 0)
  211. let carbValue = allSamples.carbs
  212. if carbValue > 0 {
  213. let carbSample = HKQuantitySample(
  214. type: carbSampleType,
  215. quantity: HKQuantity(unit: .gram(), doubleValue: Double(carbValue)),
  216. start: startDate,
  217. end: startDate,
  218. metadata: [
  219. HKMetadataKeyExternalUUID: id,
  220. HKMetadataKeySyncIdentifier: id,
  221. HKMetadataKeySyncVersion: 1
  222. ]
  223. )
  224. samples.append(carbSample)
  225. }
  226. // Fat Sample (only if value is greater than 0)
  227. if let fatValue = allSamples.fat, fatValue > 0 {
  228. let fatSample = HKQuantitySample(
  229. type: fatSampleType,
  230. quantity: HKQuantity(unit: .gram(), doubleValue: Double(fatValue)),
  231. start: startDate,
  232. end: startDate,
  233. metadata: [
  234. HKMetadataKeyExternalUUID: fpuID,
  235. HKMetadataKeySyncIdentifier: fpuID,
  236. HKMetadataKeySyncVersion: 1
  237. ]
  238. )
  239. samples.append(fatSample)
  240. }
  241. // Protein Sample (only if value is greater than 0)
  242. if let proteinValue = allSamples.protein, proteinValue > 0 {
  243. let proteinSample = HKQuantitySample(
  244. type: proteinSampleType,
  245. quantity: HKQuantity(unit: .gram(), doubleValue: Double(proteinValue)),
  246. start: startDate,
  247. end: startDate,
  248. metadata: [
  249. HKMetadataKeyExternalUUID: fpuID,
  250. HKMetadataKeySyncIdentifier: fpuID,
  251. HKMetadataKeySyncVersion: 1
  252. ]
  253. )
  254. samples.append(proteinSample)
  255. }
  256. }
  257. // Attempt to save the samples to Apple Health
  258. guard samples.isNotEmpty else {
  259. debug(.service, "No samples available for upload.")
  260. return
  261. }
  262. try await healthKitStore.save(samples)
  263. debug(.service, "Successfully stored \(samples.count) carb samples in HealthKit.")
  264. // After successful upload, update the isUploadedToHealth flag in Core Data
  265. await updateCarbsAsUploaded(carbs)
  266. } catch {
  267. debug(.service, "Failed to upload carb samples to HealthKit: \(error.localizedDescription)")
  268. }
  269. }
  270. private func updateCarbsAsUploaded(_ carbs: [CarbsEntry]) async {
  271. await backgroundContext.perform {
  272. let ids = carbs.map(\.id) as NSArray
  273. let fetchRequest: NSFetchRequest<CarbEntryStored> = CarbEntryStored.fetchRequest()
  274. fetchRequest.predicate = NSPredicate(format: "id IN %@", ids)
  275. do {
  276. let results = try self.backgroundContext.fetch(fetchRequest)
  277. for result in results {
  278. result.isUploadedToHealth = true
  279. }
  280. guard self.backgroundContext.hasChanges else { return }
  281. try self.backgroundContext.save()
  282. } catch let error as NSError {
  283. debugPrint(
  284. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to update isUploadedToHealth: \(error.userInfo)"
  285. )
  286. }
  287. }
  288. }
  289. // Insulin Upload
  290. func uploadInsulin() async {
  291. await uploadInsulin(pumpHistoryStorage.getPumpHistoryNotYetUploadedToHealth())
  292. }
  293. func uploadInsulin(_ insulinEvents: [PumpHistoryEvent]) async {
  294. guard settingsManager.settings.useAppleHealth,
  295. let sampleType = AppleHealthConfig.healthInsulinObject,
  296. checkWriteToHealthPermissions(objectTypeToHealthStore: sampleType),
  297. insulinEvents.isNotEmpty else { return }
  298. // Fetch existing temp basal entries from Core Data for the last 24 hours
  299. let fetchedInsulinEntries = await CoreDataStack.shared.fetchEntitiesAsync(
  300. ofType: PumpEventStored.self,
  301. onContext: backgroundContext,
  302. predicate: NSCompoundPredicate(andPredicateWithSubpredicates: [
  303. NSPredicate.pumpHistoryLast24h,
  304. NSPredicate(format: "tempBasal != nil")
  305. ]),
  306. key: "timestamp",
  307. ascending: true,
  308. batchSize: 50
  309. )
  310. var insulinSamples: [HKQuantitySample] = []
  311. await backgroundContext.perform {
  312. guard let existingTempBasalEntries = fetchedInsulinEntries as? [PumpEventStored] else { return }
  313. for event in insulinEvents {
  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. insulinSamples.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 { continue }
  324. let value = (Decimal(duration) / 60.0) * amount
  325. let valueRounded = self.deviceDataManager?.pumpManager?
  326. .roundToSupportedBolusVolume(units: Double(value)) ?? Double(value)
  327. // Use binary search for efficient lookup of matching entry
  328. if let matchingIndex = self.binarySearch(entries: existingTempBasalEntries, timestamp: event.timestamp) {
  329. let predecessorIndex = matchingIndex - 1
  330. if predecessorIndex >= 0 {
  331. let predecessorEntry = existingTempBasalEntries[predecessorIndex]
  332. if let adjustedSample = self.processPredecessorEntry(
  333. predecessorEntry,
  334. nextEventTimestamp: event.timestamp,
  335. sampleType: sampleType
  336. ) {
  337. insulinSamples.append(adjustedSample)
  338. }
  339. }
  340. let newEvent = PumpHistoryEvent(
  341. id: event.id,
  342. type: .tempBasal,
  343. timestamp: event.timestamp,
  344. amount: Decimal(valueRounded),
  345. duration: event.duration
  346. )
  347. if let sample = self.createSample(for: newEvent, sampleType: sampleType) {
  348. debug(.service, "Created HealthKit sample for initial temp basal entry: \(sample)")
  349. insulinSamples.append(sample)
  350. }
  351. }
  352. default:
  353. break
  354. }
  355. }
  356. }
  357. do {
  358. guard insulinSamples.isNotEmpty else {
  359. debug(.service, "No insulin samples available for upload.")
  360. return
  361. }
  362. try await healthKitStore.save(insulinSamples)
  363. debug(.service, "Successfully stored \(insulinSamples.count) insulin samples in HealthKit.")
  364. await updateInsulinAsUploaded(insulinEvents)
  365. } catch {
  366. debug(.service, "Failed to upload insulin samples to HealthKit: \(error.localizedDescription)")
  367. }
  368. }
  369. // Helper function to perform binary search on the sorted entries by timestamp
  370. private func binarySearch(entries: [PumpEventStored], timestamp: Date) -> Int? {
  371. var lowerBound = 0
  372. var upperBound = entries.count - 1
  373. while lowerBound <= upperBound {
  374. let midIndex = (lowerBound + upperBound) / 2
  375. guard let midTimestamp = entries[midIndex].timestamp else { return nil }
  376. if midTimestamp == timestamp {
  377. return midIndex
  378. } else if midTimestamp < timestamp {
  379. lowerBound = midIndex + 1
  380. } else {
  381. upperBound = midIndex - 1
  382. }
  383. }
  384. return nil
  385. }
  386. // Helper function to create a HealthKit sample from a PumpHistoryEvent
  387. private func createSample(
  388. for event: PumpHistoryEvent,
  389. sampleType: HKQuantityType
  390. ) -> HKQuantitySample? {
  391. // Ensure the event has a valid insulin amount
  392. guard let insulinValue = event.amount else { return nil }
  393. // Determine the insulin delivery reason based on the event type
  394. let deliveryReason: HKInsulinDeliveryReason
  395. switch event.type {
  396. case .bolus:
  397. deliveryReason = .bolus
  398. case .tempBasal:
  399. deliveryReason = .basal
  400. default:
  401. return nil
  402. }
  403. // Calculate the end date based on the event duration
  404. let endDate = event.timestamp.addingTimeInterval(TimeInterval(minutes: Double(event.duration ?? 0)))
  405. // Create the HealthKit quantity sample with the appropriate metadata
  406. let sample = HKQuantitySample(
  407. type: sampleType,
  408. quantity: HKQuantity(unit: .internationalUnit(), doubleValue: Double(insulinValue)),
  409. start: event.timestamp,
  410. end: endDate,
  411. metadata: [
  412. HKMetadataKeyExternalUUID: event.id,
  413. HKMetadataKeySyncIdentifier: event.id,
  414. HKMetadataKeySyncVersion: 1,
  415. HKMetadataKeyInsulinDeliveryReason: deliveryReason.rawValue,
  416. AppleHealthConfig.TrioInsulinType: deviceDataManager?.pumpManager?.status.insulinType?.title ?? ""
  417. ]
  418. )
  419. return sample
  420. }
  421. // Helper function to process a predecessor temp basal entry and adjust overlapping durations
  422. private func processPredecessorEntry(
  423. _ predecessorEntry: PumpEventStored,
  424. nextEventTimestamp: Date,
  425. sampleType: HKQuantityType
  426. ) -> HKQuantitySample? {
  427. // Ensure the predecessor entry has the necessary data
  428. guard let predecessorTimestamp = predecessorEntry.timestamp,
  429. let predecessorEntryId = predecessorEntry.id else { return nil }
  430. // Calculate the original end date of the predecessor temp basal
  431. let predecessorDurationMinutes = predecessorEntry.tempBasal?.duration ?? 0
  432. let predecessorEndDate = predecessorTimestamp.addingTimeInterval(TimeInterval(predecessorDurationMinutes * 60))
  433. // Check if the predecessor temp basal overlaps with the next event
  434. if predecessorEndDate > nextEventTimestamp {
  435. // Adjust the end date to the start of the next event to prevent overlap
  436. let adjustedEndDate = nextEventTimestamp
  437. // Precise duration in seconds
  438. let adjustedDuration = adjustedEndDate.timeIntervalSince(predecessorTimestamp)
  439. // Precise duration in hours
  440. let adjustedDurationHours = adjustedDuration / 3600
  441. // Calculate the insulin rate and adjusted delivered units
  442. let predecessorEntryRate = predecessorEntry.tempBasal?.rate?.doubleValue ?? 0
  443. let adjustedDeliveredUnits = adjustedDurationHours * predecessorEntryRate
  444. let adjustedDeliveredUnitsRounded = deviceDataManager?.pumpManager?
  445. .roundToSupportedBolusVolume(units: adjustedDeliveredUnits) ?? adjustedDeliveredUnits
  446. // Create the HealthKit quantity sample with the appropriate metadata
  447. // Intentionally do it here manually and do not use `createSample()` to handle utmost precise `end`.
  448. let sample = HKQuantitySample(
  449. type: sampleType,
  450. quantity: HKQuantity(unit: .internationalUnit(), doubleValue: Double(adjustedDeliveredUnitsRounded)),
  451. start: predecessorTimestamp,
  452. end: adjustedEndDate,
  453. metadata: [
  454. HKMetadataKeyExternalUUID: predecessorEntryId,
  455. HKMetadataKeySyncIdentifier: predecessorEntryId,
  456. HKMetadataKeySyncVersion: 2, // set the version # to 2, as we update an entry. initial version is 1.
  457. HKMetadataKeyInsulinDeliveryReason: HKInsulinDeliveryReason.basal.rawValue,
  458. AppleHealthConfig.TrioInsulinType: deviceDataManager?.pumpManager?.status.insulinType?.title ?? ""
  459. ]
  460. )
  461. debug(.service, "Created HealthKit sample for adjusted temp basal entry: \(sample)")
  462. // Create and return the HealthKit sample for the adjusted event
  463. return sample
  464. }
  465. // If there is no overlap, no adjustment is needed
  466. return nil
  467. }
  468. private func updateInsulinAsUploaded(_ insulin: [PumpHistoryEvent]) async {
  469. await backgroundContext.perform {
  470. let ids = insulin.map(\.id) as NSArray
  471. let fetchRequest: NSFetchRequest<PumpEventStored> = PumpEventStored.fetchRequest()
  472. fetchRequest.predicate = NSPredicate(format: "id IN %@", ids)
  473. do {
  474. let results = try self.backgroundContext.fetch(fetchRequest)
  475. for result in results {
  476. result.isUploadedToHealth = true
  477. }
  478. guard self.backgroundContext.hasChanges else { return }
  479. try self.backgroundContext.save()
  480. } catch let error as NSError {
  481. debugPrint(
  482. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to update isUploadedToHealth: \(error.userInfo)"
  483. )
  484. }
  485. }
  486. }
  487. // Delete Glucose/Carbs/Insulin
  488. func deleteGlucose(syncID: String) async {
  489. guard settingsManager.settings.useAppleHealth,
  490. let sampleType = AppleHealthConfig.healthBGObject,
  491. checkWriteToHealthPermissions(objectTypeToHealthStore: sampleType)
  492. else { return }
  493. let predicate = HKQuery.predicateForObjects(
  494. withMetadataKey: HKMetadataKeySyncIdentifier,
  495. operatorType: .equalTo,
  496. value: syncID
  497. )
  498. do {
  499. try await deleteObjects(of: sampleType, predicate: predicate)
  500. debug(.service, "Successfully deleted glucose sample with syncID: \(syncID)")
  501. } catch {
  502. warning(.service, "Failed to delete glucose sample with syncID: \(syncID)", error: error)
  503. }
  504. }
  505. func deleteMealData(byID id: String, sampleType: HKSampleType) async {
  506. guard settingsManager.settings.useAppleHealth else { return }
  507. let predicate = HKQuery.predicateForObjects(
  508. withMetadataKey: HKMetadataKeySyncIdentifier,
  509. operatorType: .equalTo,
  510. value: id
  511. )
  512. do {
  513. try await deleteObjects(of: sampleType, predicate: predicate)
  514. debug(.service, "Successfully deleted \(sampleType) with syncID: \(id)")
  515. } catch {
  516. warning(.service, "Failed to delete carbs sample with syncID: \(id)", error: error)
  517. }
  518. }
  519. func deleteInsulin(syncID: String) async {
  520. guard settingsManager.settings.useAppleHealth,
  521. let sampleType = AppleHealthConfig.healthInsulinObject,
  522. checkWriteToHealthPermissions(objectTypeToHealthStore: sampleType)
  523. else {
  524. debug(.service, "HealthKit permissions are not available for insulin deletion.")
  525. return
  526. }
  527. let predicate = HKQuery.predicateForObjects(
  528. withMetadataKey: HKMetadataKeySyncIdentifier,
  529. operatorType: .equalTo,
  530. value: syncID
  531. )
  532. do {
  533. try await deleteObjects(of: sampleType, predicate: predicate)
  534. debug(.service, "Successfully deleted insulin sample with syncID: \(syncID)")
  535. } catch {
  536. warning(.service, "Failed to delete insulin sample with syncID: \(syncID)", error: error)
  537. }
  538. }
  539. private func deleteObjects(of sampleType: HKSampleType, predicate: NSPredicate) async throws {
  540. try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
  541. healthKitStore.deleteObjects(of: sampleType, predicate: predicate) { success, _, error in
  542. if let error = error {
  543. continuation.resume(throwing: error)
  544. } else if success {
  545. continuation.resume(returning: ())
  546. }
  547. }
  548. }
  549. }
  550. }
  551. enum HealthKitPermissionRequestStatus {
  552. case needRequest
  553. case didRequest
  554. }
  555. enum HKError: Error {
  556. // HealthKit work only iPhone (not on iPad)
  557. case notAvailableOnCurrentDevice
  558. // Some data can be not available on current iOS-device
  559. case dataNotAvailable
  560. }
  561. private struct InsulinBolus {
  562. var id: String
  563. var amount: Decimal
  564. var date: Date
  565. }
  566. private struct InsulinBasal {
  567. var id: String
  568. var amount: Decimal
  569. var startDelivery: Date
  570. var endDelivery: Date
  571. }