| 1 | import Flutter |
| 2 | import UIKit |
| 3 | |
| 4 | @main |
| 5 | @objc class AppDelegate: FlutterAppDelegate { |
| 6 | private var backgroundTask: UIBackgroundTaskIdentifier = .invalid |
| 7 | |
| 8 | override func application( |
| 9 | _ application: UIApplication, |
| 10 | didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? |
| 11 | ) -> Bool { |
| 12 | GeneratedPluginRegistrant.register(with: self) |
| 13 | |
| 14 | let result = super.application(application, didFinishLaunchingWithOptions: launchOptions) |
| 15 | |
| 16 | guard let controller = window?.rootViewController as? FlutterViewController else { |
| 17 | return result |
| 18 | } |
| 19 | |
| 20 | let channel = FlutterMethodChannel(name: "localmind/chat_background", binaryMessenger: controller.binaryMessenger) |
| 21 | channel.setMethodCallHandler({ |
| 22 | (call: FlutterMethodCall, result: @escaping FlutterResult) -> Void in |
| 23 | switch call.method { |
| 24 | case "startForeground": |
| 25 | self.startBackgroundTask() |
| 26 | result(nil) |
| 27 | case "stopForeground": |
| 28 | self.stopBackgroundTask() |
| 29 | result(nil) |
| 30 | default: |
| 31 | result(FlutterMethodNotImplemented) |
| 32 | } |
| 33 | }) |
| 34 | |
| 35 | return result |
| 36 | } |
| 37 | |
| 38 | private func startBackgroundTask() { |
| 39 | stopBackgroundTask() |
| 40 | backgroundTask = UIApplication.shared.beginBackgroundTask { [weak self] in |
| 41 | self?.stopBackgroundTask() |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | private func stopBackgroundTask() { |
| 46 | if backgroundTask != .invalid { |
| 47 | UIApplication.shared.endBackgroundTask(backgroundTask) |
| 48 | backgroundTask = .invalid |
| 49 | } |
| 50 | } |
| 51 | } |