DataManager.swift 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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 -> [GlucoseData] {
  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. return await context.perform {
  15. guard let glucoseResults = results as? [GlucoseStored] else {
  16. return []
  17. }
  18. return glucoseResults.map {
  19. GlucoseData(glucose: Int($0.glucose), date: $0.date ?? Date(), direction: $0.directionEnum)
  20. }
  21. }
  22. }
  23. func fetchAndMapDetermination() async -> DeterminationData? {
  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", "deliverAt"]
  32. )
  33. return await context.perform {
  34. guard let determinationResults = results as? [[String: Any]] else {
  35. return nil
  36. }
  37. return 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. date: $0["deliverAt"] as? Date ?? nil
  43. )
  44. }
  45. }
  46. }
  47. func fetchAndMapOverride() async -> OverrideData? {
  48. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  49. ofType: OverrideStored.self,
  50. onContext: context,
  51. predicate: NSPredicate.predicateForOneDayAgo,
  52. key: "date",
  53. ascending: false,
  54. fetchLimit: 1,
  55. propertiesToFetch: ["enabled", "name", "target", "date", "duration"]
  56. )
  57. return await context.perform {
  58. guard let overrideResults = results as? [[String: Any]] else {
  59. return nil
  60. }
  61. return overrideResults.first.map {
  62. OverrideData(
  63. isActive: $0["enabled"] as? Bool ?? false,
  64. overrideName: $0["name"] as? String ?? "Override",
  65. date: $0["date"] as? Date ?? Date(),
  66. duration: $0["duration"] as? Decimal ?? 0,
  67. target: $0["target"] as? Decimal ?? 0
  68. )
  69. }
  70. }
  71. }
  72. }