LiveActivityBridge.swift 7.7 KB

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