DataManager.swift 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. guard let glucoseResults = results as? [GlucoseStored] else {
  15. return
  16. }
  17. await context.perform {
  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", "currentTarget"]
  32. )
  33. guard let determinationResults = results as? [[String: Any]] else {
  34. return
  35. }
  36. await context.perform {
  37. self.determination = determinationResults.first.map {
  38. DeterminationData(
  39. cob: ($0["cob"] as? Int) ?? 0,
  40. iob: ($0["iob"] as? NSDecimalNumber)?.decimalValue ?? 0,
  41. target: ($0["currentTarget"] as? NSDecimalNumber)?.decimalValue ?? 0
  42. )
  43. }
  44. }
  45. }
  46. func fetchAndMapOverride() async {
  47. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  48. ofType: OverrideStored.self,
  49. onContext: context,
  50. predicate: NSPredicate.predicateForOneDayAgo,
  51. key: "date",
  52. ascending: false,
  53. fetchLimit: 1,
  54. propertiesToFetch: ["enabled", "name"]
  55. )
  56. guard let overrideResults = results as? [[String: Any]] else {
  57. return
  58. }
  59. await context.perform {
  60. self.isOverridesActive = overrideResults.first.map {
  61. OverrideData(isActive: $0["enabled"] as? Bool ?? false, overrideName: $0["name"] as? String ?? "Override")
  62. }
  63. }
  64. }
  65. }