LiveActivityBridge.swift 6.8 KB

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