DataManager.swift 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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", "totalDailyDose", "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. tdd: ($0["totalDailyDose"] as? NSDecimalNumber)?.decimalValue ?? 0,
  42. target: ($0["currentTarget"] as? NSDecimalNumber)?.decimalValue ?? 0,
  43. date: $0["deliverAt"] as? Date ?? nil
  44. )
  45. }
  46. }
  47. }
  48. func fetchAndMapOverride() async -> OverrideData? {
  49. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  50. ofType: OverrideStored.self,
  51. onContext: context,
  52. predicate: NSPredicate.predicateForOneDayAgo,
  53. key: "date",
  54. ascending: false,
  55. fetchLimit: 1,
  56. propertiesToFetch: ["enabled", "name", "target", "date", "duration"]
  57. )
  58. return await context.perform {
  59. guard let overrideResults = results as? [[String: Any]] else {
  60. return nil
  61. }
  62. return overrideResults.first.map {
  63. OverrideData(
  64. isActive: $0["enabled"] as? Bool ?? false,
  65. overrideName: $0["name"] as? String ?? "Override",
  66. date: $0["date"] as? Date ?? Date(),
  67. duration: $0["duration"] as? Decimal ?? 0,
  68. target: $0["target"] as? Decimal ?? 0
  69. )
  70. }
  71. }
  72. }
  73. }