Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -120,10 +120,14 @@ public class SwiftFlutterForegroundTaskPlugin: NSObject, FlutterPlugin {
}

BackgroundServiceStatus.setData(action: BackgroundServiceAction.APP_TERMINATE)
BackgroundService.sharedInstance.run()
var isDestroyed = false
BackgroundService.sharedInstance.run(onDestroyed: { isDestroyed = true })

// Chance to handle onDestroy before app terminates
sleep(5)
// Wait for onDestroy (max 2s); spin run loop so its reply is served. System allows ~5s total.
let deadline = Date().addingTimeInterval(2)
while !isDestroyed && Date() < deadline {
RunLoop.current.run(mode: .default, before: deadline)
}
}

// ================= Service Delegate =================
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ class BackgroundService: NSObject {
super.init()
}

func run() {
func run(onDestroyed: @escaping () -> Void = {}) {
backgroundServiceStatus = BackgroundServiceStatus.getData()
notificationOptions = NotificationOptions.getData()
notificationContent = NotificationContent.getData()
Expand Down Expand Up @@ -93,7 +93,7 @@ class BackgroundService: NSObject {
}
break
case .API_STOP, .APP_TERMINATE:
destroyForegroundTask()
destroyForegroundTask(onDestroyed: onDestroyed)
removeAllNotification()
isRunningService = false
break
Expand Down Expand Up @@ -199,8 +199,12 @@ class BackgroundService: NSObject {
foregroundTask?.update(taskEventAction: currForegroundTaskOptions.eventAction)
}

private func destroyForegroundTask() {
foregroundTask?.destroy()
private func destroyForegroundTask(onDestroyed: @escaping () -> Void = {}) {
if let foregroundTask = foregroundTask {
foregroundTask.destroy(onDestroyed: onDestroyed)
} else {
onDestroyed()
}
foregroundTask = nil
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,11 @@ class ForegroundTask {
}
}

func destroy() {
func destroy(onDestroyed: @escaping () -> Void = {}) {
if isDestroyed {
onDestroyed()
return
}
runIfNotDestroyed {
stopRepeatTask()

Expand All @@ -164,10 +168,15 @@ class ForegroundTask {
taskLifecycleListener.onEngineWillDestroy()
flutterEngine?.destroyContext()
flutterEngine = nil
onDestroyed()
} else {
if backgroundChannel == nil {
onDestroyed()
}
backgroundChannel?.invokeMethod(ACTION_TASK_DESTROY, arguments: nil) { _ in
self.flutterEngine?.destroyContext()
self.flutterEngine = nil
onDestroyed()
}
taskLifecycleListener.onTaskDestroy()
taskLifecycleListener.onEngineWillDestroy()
Expand Down