DataManager.swift 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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"]
  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. )
  43. }
  44. }
  45. }
  46. func fetchAndMapOverride() async -> OverrideData? {
  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", "target", "date", "duration"]
  55. )
  56. return await context.perform {
  57. guard let overrideResults = results as? [[String: Any]] else {
  58. return nil
  59. }
  60. return overrideResults.first.map {
  61. OverrideData(
  62. isActive: $0["enabled"] as? Bool ?? false,
  63. overrideName: $0["name"] as? String ?? "Override",
  64. date: $0["date"] as? Date ?? Date(),
  65. duration: $0["duration"] as? Decimal ?? 0,
  66. target: $0["target"] as? Decimal ?? 0
  67. )
  68. }
  69. }
  70. }
  71. }