I have a flutter project that contains some native code, in this case I have a background task using BGTaskScheduler
(using native swift), ok now the problem is that the task is never executed and even simulating it using xcode with the option : Debug -> Simulate Background Fetch it nothing happens , let me show my code.
.......
......
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
initPlatformChannelAndCallMethod()
.....
.....
self.registerTaskForLocation()
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
private func registerTaskForLocation(){
self.isTaskRegistered = BGTaskScheduler.shared.register(forTaskWithIdentifier:
"com.myapp.bgtasklocation", using: nil) { task in
let operationQuee = OperationQueue()
print("Background executing")
let locationOperation = BlockOperation {
// execution of the main task
}
task.expirationHandler = {
locationOperation.cancel()
}
locationOperation.completionBlock = {
task.setTaskCompleted(success: !locationOperation.isCancelled )
}
operationQuee.addOperation( locationOperation )
}
print("Task registered \(self.isTaskRegistered)")
}
private func scheduleThetaskRegistered(){
let taskRequest = BGAppRefreshTaskRequest(identifier: "com.
myapp.bgtasklocation")
print("BGTask task requested with identifier")
taskRequest.earliestBeginDate = Date(timeIntervalSinceNow: 2 * 60)
print("BGTask added earliest start for bgtask")
do {
print("BGTask now will be submited")
try BGTaskScheduler.shared.submit( taskRequest )
} catch {
print("BGTask Could not schedule app refresh: \(error)")
}
}
now so far the task is submited without problem and the print that is inside the
catch in scheduleThetaskRegistered method is not printed so I guess this task is
submited.
I already added the task identifier in info.plist and I enabled the background fetch in background modes.
<key>BGTaskSchedulerPermittedIdentifiers</key>
<array>
<string>com.myapp.bgtasklocation</string>
</array>
now when I move the app to background and start a simulation of background task in Xcode
using its debug mode: Debug -> Simulate Background Fetch.
Nothing happen and my code that is inside the BlocOperation is not triggered.
after trying some times at one moment I got this error after taping the option :
Simulate Background Fetch.
[BackgroundTask] Background Task 54 (“Flutter debug task”), was created over 30 seconds ago. In applications running in the background, this creates a risk of termination. Remember to call UIApplication.endBackgroundTask(_:) for your task in a timely manner to avoid this.