ソースを参照

Change glucose fetch timer depending on back or foreground

When app goes to background, the glucose fetch timer is changed to 1 second
When app goes to foreground, the glucose fetch timer is changed to 1 minute

This may save some battery when app is in foreground. In foreground 1 minute timer is ok
Johan Degraeve 3 年 前
コミット
ecd754da8b
1 ファイル変更33 行追加1 行削除
  1. 33 1
      FreeAPS/Sources/APS/FetchGlucoseManager.swift

+ 33 - 1
FreeAPS/Sources/APS/FetchGlucoseManager.swift

@@ -1,5 +1,6 @@
 import Combine
 import Foundation
+import SpriteKit
 import SwiftDate
 import Swinject
 
@@ -7,6 +8,9 @@ protocol FetchGlucoseManager: SourceInfoProvider {}
 
 final class BaseFetchGlucoseManager: FetchGlucoseManager, Injectable {
     private let processQueue = DispatchQueue(label: "BaseGlucoseManager.processQueue")
+
+    private let notificationCenter = Foundation.NotificationCenter.default
+
     @Injected() var glucoseStorage: GlucoseStorage!
     @Injected() var nightscoutManager: NightscoutManager!
     @Injected() var apsManager: APSManager!
@@ -16,7 +20,9 @@ final class BaseFetchGlucoseManager: FetchGlucoseManager, Injectable {
     @Injected() var deviceDataManager: DeviceDataManager!
 
     private var lifetime = Lifetime()
-    private let timer = DispatchTimer(timeInterval: TimeInterval(1.0))
+
+    /// timer to fetch glucose, initially set to 1 minute. If app goes to background it will be changed to 1 second
+    private var timer = DispatchTimer(timeInterval: TimeInterval(minutes: 1.0))
 
     private lazy var dexcomSource = DexcomSource()
     private lazy var simulatorSource = GlucoseSimulatorSource()
@@ -25,10 +31,36 @@ final class BaseFetchGlucoseManager: FetchGlucoseManager, Injectable {
         injectServices(resolver)
         updateGlucoseSource()
         subscribe()
+
+        notificationCenter.addObserver(
+            self,
+            selector: #selector(didEnterBackground(_:)),
+            name: UIApplication.didEnterBackgroundNotification,
+            object: nil
+        )
+
+        notificationCenter.addObserver(
+            self,
+            selector: #selector(willEnterForeground(_:)),
+            name: UIApplication.willEnterForegroundNotification,
+            object: nil
+        )
     }
 
     var glucoseSource: GlucoseSource!
 
+    /// change timer to 1 second
+    @objc private func didEnterBackground(_: Notification) {
+        timer = DispatchTimer(timeInterval: TimeInterval(1.0))
+        subscribe()
+    }
+
+    /// change timer to 1 minute
+    @objc private func willEnterForeground(_: Notification) {
+        timer = DispatchTimer(timeInterval: TimeInterval(minutes: 1.0))
+        subscribe()
+    }
+
     private func updateGlucoseSource() {
         switch settingsManager.settings.cgm {
         case .xdrip: