|
| 1 | +// |
| 2 | +// BackgroundWorker.swift |
| 3 | +// workmanager |
| 4 | +// |
| 5 | +// Created by Sebastian Roth on 10/06/2021. |
| 6 | +// |
| 7 | + |
| 8 | +import Foundation |
| 9 | + |
| 10 | +enum BackgroundMode { |
| 11 | + case backgroundFetch |
| 12 | + case backgroundProcessingTask(identifier: String) |
| 13 | + case backgroundPeriodicTask(identifier: String) |
| 14 | + case backgroundOneOffTask(identifier: String) |
| 15 | + |
| 16 | + var flutterThreadlabelPrefix: String { |
| 17 | + switch self { |
| 18 | + case .backgroundFetch: |
| 19 | + return "\(SwiftWorkmanagerPlugin.identifier).BackgroundFetch" |
| 20 | + case .backgroundProcessingTask: |
| 21 | + return "\(SwiftWorkmanagerPlugin.identifier).BackgroundProcessingTask" |
| 22 | + case .backgroundPeriodicTask: |
| 23 | + return "\(SwiftWorkmanagerPlugin.identifier).BackgroundPeriodicTask" |
| 24 | + case .backgroundOneOffTask: |
| 25 | + return "\(SwiftWorkmanagerPlugin.identifier).OneOffTask" |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + var onResultSendArguments: [String: String] { |
| 30 | + switch self { |
| 31 | + case .backgroundFetch: |
| 32 | + return ["\(SwiftWorkmanagerPlugin.identifier).DART_TASK": "iOSPerformFetch"] |
| 33 | + case let .backgroundProcessingTask(identifier): |
| 34 | + return ["\(SwiftWorkmanagerPlugin.identifier).DART_TASK": identifier] |
| 35 | + case let .backgroundPeriodicTask(identifier): |
| 36 | + return ["\(SwiftWorkmanagerPlugin.identifier).DART_TASK": identifier] |
| 37 | + case let .backgroundOneOffTask(identifier): |
| 38 | + return ["\(SwiftWorkmanagerPlugin.identifier).DART_TASK": identifier] |
| 39 | + } |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +class BackgroundWorker { |
| 44 | + |
| 45 | + let backgroundMode: BackgroundMode |
| 46 | + let flutterPluginRegistrantCallback: FlutterPluginRegistrantCallback? |
| 47 | + let inputData: String |
| 48 | + |
| 49 | + init(mode: BackgroundMode, inputData: String, flutterPluginRegistrantCallback: FlutterPluginRegistrantCallback?) { |
| 50 | + backgroundMode = mode |
| 51 | + self.inputData = inputData |
| 52 | + self.flutterPluginRegistrantCallback = flutterPluginRegistrantCallback |
| 53 | + } |
| 54 | + |
| 55 | + private struct BackgroundChannel { |
| 56 | + static let name = "\(SwiftWorkmanagerPlugin.identifier)/background_channel_work_manager" |
| 57 | + static let initialized = "backgroundChannelInitialized" |
| 58 | + static let onResultSendCommand = "onResultSend" |
| 59 | + } |
| 60 | + |
| 61 | + /// The result is discardable due to how [BackgroundTaskOperation] works. |
| 62 | + @discardableResult |
| 63 | + func performBackgroundRequest(_ completionHandler: @escaping (UIBackgroundFetchResult) -> Void) -> Bool { |
| 64 | + guard let callbackHandle = UserDefaultsHelper.getStoredCallbackHandle(), |
| 65 | + let flutterCallbackInformation = FlutterCallbackCache.lookupCallbackInformation(callbackHandle) |
| 66 | + else { |
| 67 | + logError("[\(String(describing: self))] \(WMPError.workmanagerNotInitialized.message)") |
| 68 | + completionHandler(.failed) |
| 69 | + return false |
| 70 | + } |
| 71 | + |
| 72 | + let taskSessionStart = Date() |
| 73 | + let taskSessionIdentifier = UUID() |
| 74 | + |
| 75 | + let debugHelper = DebugNotificationHelper(taskSessionIdentifier) |
| 76 | + debugHelper.showStartFetchNotification( |
| 77 | + startDate: taskSessionStart, |
| 78 | + callBackHandle: callbackHandle, |
| 79 | + callbackInfo: flutterCallbackInformation |
| 80 | + ) |
| 81 | + |
| 82 | + var flutterEngine: FlutterEngine? = FlutterEngine( |
| 83 | + name: backgroundMode.flutterThreadlabelPrefix, |
| 84 | + project: nil, |
| 85 | + allowHeadlessExecution: true |
| 86 | + ) |
| 87 | + |
| 88 | + flutterEngine!.run( |
| 89 | + withEntrypoint: flutterCallbackInformation.callbackName, |
| 90 | + libraryURI: flutterCallbackInformation.callbackLibraryPath |
| 91 | + ) |
| 92 | + flutterPluginRegistrantCallback?(flutterEngine!) |
| 93 | + |
| 94 | + var backgroundMethodChannel: FlutterMethodChannel? = FlutterMethodChannel( |
| 95 | + name: BackgroundChannel.name, |
| 96 | + binaryMessenger: flutterEngine!.binaryMessenger |
| 97 | + ) |
| 98 | + |
| 99 | + func cleanupFlutterResources() { |
| 100 | + flutterEngine?.destroyContext() |
| 101 | + backgroundMethodChannel = nil |
| 102 | + flutterEngine = nil |
| 103 | + } |
| 104 | + |
| 105 | + backgroundMethodChannel?.setMethodCallHandler { call, result in |
| 106 | + switch call.method { |
| 107 | + case BackgroundChannel.initialized: |
| 108 | + result(true) // Agree to Flutter's method invocation |
| 109 | + var arguments = self.backgroundMode.onResultSendArguments |
| 110 | + if self.inputData != "" { |
| 111 | + arguments = arguments.merging(["be.tramckrijte.workmanager.INPUT_DATA": self.inputData]) { current, _ in current } |
| 112 | + } |
| 113 | + |
| 114 | + backgroundMethodChannel?.invokeMethod( |
| 115 | + BackgroundChannel.onResultSendCommand, |
| 116 | + arguments: arguments, |
| 117 | + result: { flutterResult in |
| 118 | + cleanupFlutterResources() |
| 119 | + let taskSessionCompleter = Date() |
| 120 | + let result: UIBackgroundFetchResult = (flutterResult as? Bool ?? false) ? .newData : .failed |
| 121 | + let taskDuration = taskSessionCompleter.timeIntervalSince(taskSessionStart) |
| 122 | + logInfo("[\(String(describing: self))] \(#function) -> performBackgroundRequest.\(result) (finished in \(taskDuration.formatToSeconds()))") |
| 123 | + |
| 124 | + debugHelper.showCompletedFetchNotification( |
| 125 | + completedDate: taskSessionCompleter, |
| 126 | + result: result, |
| 127 | + elapsedTime: taskDuration |
| 128 | + ) |
| 129 | + completionHandler(result) |
| 130 | + }) |
| 131 | + default: |
| 132 | + result(WMPError.unhandledMethod(call.method).asFlutterError) |
| 133 | + cleanupFlutterResources() |
| 134 | + completionHandler(UIBackgroundFetchResult.failed) |
| 135 | + } |
| 136 | + } |
| 137 | + |
| 138 | + return true |
| 139 | + } |
| 140 | +} |
0 commit comments