DataManager.swift 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import Foundation
  2. // Fetch Data for Glucose and Determination from Core Data and map them to the Structs in order to pass them thread safe to the glucoseDidUpdate/ pushUpdate function
  3. @available(iOS 16.2, *)
  4. extension LiveActivityBridge {
  5. func fetchAndMapGlucose() async {
  6. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  7. ofType: GlucoseStored.self,
  8. onContext: context,
  9. predicate: NSPredicate.predicateForSixHoursAgo,
  10. key: "date",
  11. ascending: false,
  12. fetchLimit: 72
  13. )
  14. await context.perform {
  15. guard let glucoseResults = results as? [GlucoseStored] else {
  16. return
  17. }
  18. self.glucoseFromPersistence = glucoseResults.map {
  19. GlucoseData(glucose: Int($0.glucose), date: $0.date ?? Date(), direction: $0.directionEnum)
  20. }
  21. }
  22. }
  23. func fetchAndMapDetermination() async {
  24. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  25. ofType: OrefDetermination.self,
  26. onContext: context,
  27. predicate: NSPredicate.predicateFor30MinAgoForDetermination,
  28. key: "deliverAt",
  29. ascending: false,
  30. fetchLimit: 1,
  31. propertiesToFetch: ["iob", "cob"]
  32. )
  33. await context.perform {
  34. guard let determinationResults = results as? [[String: Any]] else {
  35. return
  36. }
  37. self.determination = determinationResults.first.map {
  38. DeterminationData(
  39. cob: ($0["cob"] as? Int) ?? 0,
  40. iob: ($0["iob"] as? NSDecimalNumber)?.decimalValue ?? 0
  41. )
  42. }
  43. }
  44. }
  45. func fetchAndMapOverride() async {
  46. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  47. ofType: OverrideStored.self,
  48. onContext: context,
  49. predicate: NSPredicate.predicateForOneDayAgo,
  50. key: "date",
  51. ascending: false,
  52. fetchLimit: 1,
  53. propertiesToFetch: ["enabled"]
  54. )
  55. await context.perform {
  56. guard let overrideResults = results as? [[String: Any]] else {
  57. return
  58. }
  59. self.isOverridesActive = overrideResults.first.map {
  60. OverrideData(isActive: $0["enabled"] as? Bool ?? false)
  61. }
  62. }
  63. }
  64. }