Просмотр исходного кода

Add expiration handler in beginBackgroundTask method

Marvin Polscheit недель назад: 2
Родитель
Сommit
b64aa73628
1 измененных файлов с 17 добавлено и 6 удалено
  1. 17 6
      Trio/Sources/APS/APSManager.swift

+ 17 - 6
Trio/Sources/APS/APSManager.swift

@@ -267,8 +267,18 @@ final class BaseAPSManager: APSManager, Injectable {
                 return
             }
 
-            // Local background-task identifier — no shared mutable state.
-            let bgTask = await UIApplication.shared.beginBackgroundTask(withName: "Loop starting")
+            // Start background task
+            // we probably need to refactor this when implementing Swift 6 due to mutation of a captured var in an async context
+            var taskID: UIBackgroundTaskIdentifier = .invalid
+            taskID = await UIApplication.shared.beginBackgroundTask(withName: "Loop starting") {
+                // closure runs on the Main Thread
+                // removed the Task that provided no guarantee to end the background task
+                if taskID != .invalid {
+                    UIApplication.shared.endBackgroundTask(taskID)
+                    taskID = .invalid
+                }
+            }
+
             isLooping.send(true)
 
             let loopStartDate = Date()
@@ -297,16 +307,17 @@ final class BaseAPSManager: APSManager, Injectable {
                 debug(.apsManager, "\(DebuggingIdentifiers.failed) Failed to complete Loop: \(error)")
             }
 
-            // End the background task on the async path itself
-            if bgTask != .invalid {
-                await UIApplication.shared.endBackgroundTask(bgTask)
+            // End the background task
+            if taskID != .invalid {
+                await UIApplication.shared.endBackgroundTask(taskID)
+                taskID = .invalid
             }
         }
     }
 
     private func executeLoop(loopStatRecord: inout LoopStats) async throws {
         try await determineBasal()
-        
+
         // Closed loop: also enact the determination.
         if settings.closedLoop {
             try await enactDetermination()