The flutter_background_service package provides a convenient way to run background tasks on both Android and iOS platforms in Flutter. However, for iOS platform, you still need to implement the BGTaskScheduler in your AppDelegate.swift file to handle background tasks.
The BGTaskScheduler is an iOS framework that allows you to schedule and handle background tasks on your app. It is responsible for scheduling your app's background fetch tasks and launching your app in the background to perform those tasks.
To use BGTaskScheduler with flutter_background_service package, you can create a custom task that will be scheduled by BGTaskScheduler and then call the start() method provided by the flutter_background_service package to start the task.
Here is an example code snippet:
import UIKit
import Flutter
import flutter_background_service
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var flutterEngine : FlutterEngine?;
var task: UIBackgroundTaskIdentifier = .invalid
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
flutterEngine = FlutterEngine(name: "my_engine")
flutterEngine?.run()
return true
}
func applicationDidEnterBackground(_ application: UIApplication) {
task = UIApplication.shared.beginBackgroundTask(withName: "myBackgroundTask") {
self.endTask()
}
BackgroundService.initialize(isolateName: "myIsolate", callback: myTask)
BackgroundService.registerHeadlessTask()
BackgroundTaskScheduler.init().register(
forTaskWithIdentifier: "myBackgroundTask",
using: nil) { task in
self.handleAppRefreshTask(task: task as! BGAppRefreshTask)
}
}
func handleAppRefreshTask(task: BGAppRefreshTask) {
task.expirationHandler = {
self.endTask()
}
BackgroundService.performTask()
task.setTaskCompleted(success: true)
self.endTask()
}
func myTask() {
// Perform your background task here
// ...
BackgroundService.finish(taskId: task)
}
func endTask() {
UIApplication.shared.endBackgroundTask(task)
task = .invalid
}
}
In this example, the handleAppRefreshTask function is registered as the handler for the BGAppRefreshTask task. It calls the myTask function provided by flutter_background_service package to perform the actual background task.
Note that you will also need to add the BGTaskSchedulerPermittedIdentifiers key to your app's Info.plist file and include the identifier for your custom task to allow BGTaskScheduler to schedule your task.
<key>BGTaskSchedulerPermittedIdentifiers</key>
<array>
<string>myBackgroundTask</string>
</array>
With this implementation, your background task will be automatically scheduled and launched by iOS at the specified interval, and you can use the flutter_background_service package to perform your background tasks in a separate isolate.