LiveActivityBridge.swift 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. import ActivityKit
  2. import Foundation
  3. import Swinject
  4. import UIKit
  5. extension LiveActivityAttributes.ContentState {
  6. static func formatGlucose(_ value: Int, mmol: Bool, forceSign: Bool) -> String {
  7. let formatter = NumberFormatter()
  8. formatter.numberStyle = .decimal
  9. formatter.maximumFractionDigits = 0
  10. if mmol {
  11. formatter.minimumFractionDigits = 1
  12. formatter.maximumFractionDigits = 1
  13. }
  14. if forceSign {
  15. formatter.positivePrefix = formatter.plusSign
  16. }
  17. formatter.roundingMode = .halfUp
  18. return formatter
  19. .string(from: mmol ? value.asMmolL as NSNumber : NSNumber(value: value))!
  20. }
  21. init?(new bg: BloodGlucose, prev: BloodGlucose?, mmol: Bool, chart: [Readings], settings: FreeAPSSettings) {
  22. guard let glucose = bg.glucose,
  23. bg.dateString.timeIntervalSinceNow > -TimeInterval(minutes: 6)
  24. else {
  25. return nil
  26. }
  27. let formattedBG = Self.formatGlucose(glucose, mmol: mmol, forceSign: false)
  28. let trendString: String?
  29. var rotationDegrees: Double = 0.0
  30. switch bg.direction {
  31. case .doubleUp,
  32. .singleUp,
  33. .tripleUp:
  34. trendString = "arrow.up"
  35. rotationDegrees = -90
  36. case .fortyFiveUp:
  37. trendString = "arrow.up.right"
  38. rotationDegrees = -45
  39. case .flat:
  40. trendString = "arrow.right"
  41. rotationDegrees = 0
  42. case .fortyFiveDown:
  43. trendString = "arrow.down.right"
  44. rotationDegrees = 45
  45. case .doubleDown,
  46. .singleDown,
  47. .tripleDown:
  48. trendString = "arrow.down"
  49. rotationDegrees = 90
  50. case .notComputable,
  51. Optional.none,
  52. .rateOutOfRange,
  53. .some(.none):
  54. trendString = nil
  55. rotationDegrees = 0
  56. }
  57. let change = prev?.glucose.map({
  58. Self.formatGlucose(glucose - $0, mmol: mmol, forceSign: true)
  59. }) ?? ""
  60. let chartBG = chart.map(\.glucose)
  61. let conversionFactor: Double = settings.units == .mmolL ? 18.0 : 1.0
  62. let convertedChartBG = chartBG.map { Double($0) / conversionFactor }
  63. let chartDate = chart.map(\.date)
  64. self.init(
  65. bg: formattedBG,
  66. trendSystemImage: trendString,
  67. change: change,
  68. date: bg.dateString,
  69. chart: convertedChartBG,
  70. chartDate: chartDate, rotationDegrees: rotationDegrees
  71. )
  72. }
  73. }
  74. @available(iOS 16.2, *) private struct ActiveActivity {
  75. let activity: Activity<LiveActivityAttributes>
  76. let startDate: Date
  77. func needsRecreation() -> Bool {
  78. switch activity.activityState {
  79. case .dismissed,
  80. .ended:
  81. return true
  82. case .active,
  83. .stale: break
  84. @unknown default:
  85. return true
  86. }
  87. return -startDate.timeIntervalSinceNow >
  88. TimeInterval(60 * 60)
  89. }
  90. }
  91. @available(iOS 16.2, *) final class LiveActivityBridge: Injectable {
  92. @Injected() private var settingsManager: SettingsManager!
  93. @Injected() private var glucoseStorage: GlucoseStorage!
  94. @Injected() private var broadcaster: Broadcaster!
  95. private var settings: FreeAPSSettings {
  96. settingsManager.settings
  97. }
  98. private var currentActivity: ActiveActivity?
  99. private var latestGlucose: BloodGlucose?
  100. init(resolver: Resolver) {
  101. injectServices(resolver)
  102. broadcaster.register(GlucoseObserver.self, observer: self)
  103. Foundation.NotificationCenter.default.addObserver(
  104. forName: UIApplication.didEnterBackgroundNotification,
  105. object: nil,
  106. queue: nil
  107. ) { _ in
  108. self.forceActivityUpdate()
  109. }
  110. Foundation.NotificationCenter.default.addObserver(
  111. forName: UIApplication.didBecomeActiveNotification,
  112. object: nil,
  113. queue: nil
  114. ) { _ in
  115. self.forceActivityUpdate()
  116. }
  117. }
  118. /// creates and tries to present a new activity update from the current GlucoseStorage values if live activities are enabled in settings
  119. /// Ends existing live activities if live activities are not enabled in settings
  120. private func forceActivityUpdate() {
  121. // just before app resigns active, show a new activity
  122. // only do this if there is no current activity or the current activity is older than 1h
  123. if settings.useLiveActivity {
  124. if currentActivity?.needsRecreation() ?? true
  125. {
  126. glucoseDidUpdate(glucoseStorage.recent())
  127. }
  128. } else {
  129. Task {
  130. await self.endActivity()
  131. }
  132. }
  133. }
  134. /// attempts to present this live activity state, creating a new activity if none exists yet
  135. @MainActor private func pushUpdate(_ state: LiveActivityAttributes.ContentState) async {
  136. // hide duplicate/unknown activities
  137. for unknownActivity in Activity<LiveActivityAttributes>.activities
  138. .filter({ self.currentActivity?.activity.id != $0.id })
  139. {
  140. await unknownActivity.end(nil, dismissalPolicy: .immediate)
  141. }
  142. let content = ActivityContent(state: state, staleDate: state.date.addingTimeInterval(TimeInterval(6 * 60)))
  143. if let currentActivity {
  144. if currentActivity.needsRecreation(), UIApplication.shared.applicationState == .active {
  145. // activity is no longer visible or old. End it and try to push the update again
  146. await endActivity()
  147. await pushUpdate(state)
  148. } else {
  149. await currentActivity.activity.update(content)
  150. }
  151. } else {
  152. do {
  153. let activity = try Activity.request(
  154. attributes: LiveActivityAttributes(startDate: Date.now),
  155. content: content,
  156. pushType: nil
  157. )
  158. currentActivity = ActiveActivity(activity: activity, startDate: Date.now)
  159. } catch {
  160. print("activity creation error: \(error)")
  161. }
  162. }
  163. }
  164. /// ends all live activities immediateny
  165. private func endActivity() async {
  166. if let currentActivity {
  167. await currentActivity.activity.end(nil, dismissalPolicy: ActivityUIDismissalPolicy.immediate)
  168. self.currentActivity = nil
  169. }
  170. // end any other activities
  171. for unknownActivity in Activity<LiveActivityAttributes>.activities {
  172. await unknownActivity.end(nil, dismissalPolicy: .immediate)
  173. }
  174. }
  175. }
  176. @available(iOS 16.2, *)
  177. extension LiveActivityBridge: GlucoseObserver {
  178. func glucoseDidUpdate(_ glucose: [BloodGlucose]) {
  179. // backfill latest glucose if contained in this update
  180. if glucose.count > 1 {
  181. latestGlucose = glucose[glucose.count - 2]
  182. }
  183. defer {
  184. self.latestGlucose = glucose.last
  185. }
  186. // fetch glucose for chart from Core Data
  187. let coreDataStorage = CoreDataStorage()
  188. let sixHoursAgo = Calendar.current.date(byAdding: .hour, value: -6, to: Date()) ?? Date()
  189. let fetchGlucose = coreDataStorage.fetchGlucose(interval: sixHoursAgo as NSDate)
  190. guard let bg = glucose.last, let content = LiveActivityAttributes.ContentState(
  191. new: bg,
  192. prev: latestGlucose,
  193. mmol: settings.units == .mmolL,
  194. chart: fetchGlucose, settings: settings
  195. ) else {
  196. // no bg or value stale. Don't update the activity if there already is one, just let it turn stale so that it can still be used once current bg is available again
  197. return
  198. }
  199. Task {
  200. await self.pushUpdate(content)
  201. }
  202. }
  203. }