LiveActivityBridge.swift 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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: [BloodGlucose]) {
  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. switch bg.direction {
  30. case .doubleUp,
  31. .singleUp,
  32. .tripleUp:
  33. trendString = "arrow.up"
  34. case .fortyFiveUp:
  35. trendString = "arrow.up.right"
  36. case .flat:
  37. trendString = "arrow.right"
  38. case .fortyFiveDown:
  39. trendString = "arrow.down.right"
  40. case .doubleDown,
  41. .singleDown,
  42. .tripleDown:
  43. trendString = "arrow.down"
  44. case .notComputable,
  45. Optional.none,
  46. .rateOutOfRange,
  47. .some(.none):
  48. trendString = nil
  49. }
  50. let change = prev?.glucose.map({
  51. Self.formatGlucose(glucose - $0, mmol: mmol, forceSign: true)
  52. }) ?? ""
  53. let chartBG = chart.map(\.glucose)
  54. let chartDate = chart.map(\.dateString)
  55. self.init(
  56. bg: formattedBG,
  57. trendSystemImage: trendString,
  58. change: change,
  59. date: bg.dateString,
  60. chart: chartBG,
  61. chartDate: chartDate
  62. )
  63. }
  64. }
  65. @available(iOS 16.2, *) private struct ActiveActivity {
  66. let activity: Activity<LiveActivityAttributes>
  67. let startDate: Date
  68. func needsRecreation() -> Bool {
  69. switch activity.activityState {
  70. case .dismissed,
  71. .ended:
  72. return true
  73. case .active,
  74. .stale: break
  75. @unknown default:
  76. return true
  77. }
  78. return -startDate.timeIntervalSinceNow >
  79. TimeInterval(60 * 60)
  80. }
  81. }
  82. @available(iOS 16.2, *) final class LiveActivityBridge: Injectable {
  83. @Injected() private var settingsManager: SettingsManager!
  84. @Injected() private var glucoseStorage: GlucoseStorage!
  85. @Injected() private var broadcaster: Broadcaster!
  86. private var settings: FreeAPSSettings {
  87. settingsManager.settings
  88. }
  89. private var currentActivity: ActiveActivity?
  90. private var latestGlucose: BloodGlucose?
  91. init(resolver: Resolver) {
  92. injectServices(resolver)
  93. broadcaster.register(GlucoseObserver.self, observer: self)
  94. Foundation.NotificationCenter.default.addObserver(
  95. forName: UIApplication.didEnterBackgroundNotification,
  96. object: nil,
  97. queue: nil
  98. ) { _ in
  99. self.forceActivityUpdate()
  100. }
  101. Foundation.NotificationCenter.default.addObserver(
  102. forName: UIApplication.didBecomeActiveNotification,
  103. object: nil,
  104. queue: nil
  105. ) { _ in
  106. self.forceActivityUpdate()
  107. }
  108. }
  109. /// creates and tries to present a new activity update from the current GlucoseStorage values if live activities are enabled in settings
  110. /// Ends existing live activities if live activities are not enabled in settings
  111. private func forceActivityUpdate() {
  112. // just before app resigns active, show a new activity
  113. // only do this if there is no current activity or the current activity is older than 1h
  114. if settings.useLiveActivity {
  115. if currentActivity?.needsRecreation() ?? true
  116. {
  117. glucoseDidUpdate(glucoseStorage.recent())
  118. }
  119. } else {
  120. Task {
  121. await self.endActivity()
  122. }
  123. }
  124. }
  125. /// attempts to present this live activity state, creating a new activity if none exists yet
  126. @MainActor private func pushUpdate(_ state: LiveActivityAttributes.ContentState) async {
  127. // hide duplicate/unknown activities
  128. for unknownActivity in Activity<LiveActivityAttributes>.activities
  129. .filter({ self.currentActivity?.activity.id != $0.id })
  130. {
  131. await unknownActivity.end(nil, dismissalPolicy: .immediate)
  132. }
  133. let content = ActivityContent(state: state, staleDate: state.date.addingTimeInterval(TimeInterval(6 * 60)))
  134. if let currentActivity {
  135. if currentActivity.needsRecreation(), UIApplication.shared.applicationState == .active {
  136. // activity is no longer visible or old. End it and try to push the update again
  137. await endActivity()
  138. await pushUpdate(state)
  139. } else {
  140. await currentActivity.activity.update(content)
  141. }
  142. } else {
  143. do {
  144. let activity = try Activity.request(
  145. attributes: LiveActivityAttributes(startDate: Date.now),
  146. content: content,
  147. pushType: nil
  148. )
  149. currentActivity = ActiveActivity(activity: activity, startDate: Date.now)
  150. } catch {
  151. print("activity creation error: \(error)")
  152. }
  153. }
  154. }
  155. /// ends all live activities immediateny
  156. private func endActivity() async {
  157. if let currentActivity {
  158. await currentActivity.activity.end(nil, dismissalPolicy: ActivityUIDismissalPolicy.immediate)
  159. self.currentActivity = nil
  160. }
  161. // end any other activities
  162. for unknownActivity in Activity<LiveActivityAttributes>.activities {
  163. await unknownActivity.end(nil, dismissalPolicy: .immediate)
  164. }
  165. }
  166. }
  167. @available(iOS 16.2, *)
  168. extension LiveActivityBridge: GlucoseObserver {
  169. func glucoseDidUpdate(_ glucose: [BloodGlucose]) {
  170. // backfill latest glucose if contained in this update
  171. if glucose.count > 1 {
  172. latestGlucose = glucose[glucose.count - 2]
  173. }
  174. defer {
  175. self.latestGlucose = glucose.last
  176. }
  177. let last72Glucose = Array(glucose.dropLast().suffix(72))
  178. guard let bg = glucose.last, let content = LiveActivityAttributes.ContentState(
  179. new: bg,
  180. prev: latestGlucose,
  181. mmol: settings.units == .mmolL,
  182. chart: last72Glucose
  183. ) else {
  184. // 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
  185. return
  186. }
  187. Task {
  188. await self.pushUpdate(content)
  189. }
  190. }
  191. }