Is there any possible way to run a background task in an iOS App when the app is forced quit or when the app is not in the App Switcher?
Running Tasks when the app is not in the App switcher
See my explanation of this in iOS Background Execution Limits.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
Thank you @DTS Engineer. As per the WWDC 2019 video, I've updated the native code to run a background task every 15 minutes in my Flutter project. However, it does not work for me.
After adding fetch
to the background modes in the capabilities and adding task_id
to the Info.plist
, I added the following code block to the AppDelegate.swift
. Despite this, it didn't work for me. When I simulated this as per the video, it did not simulate periodically like it happens in the video but only ran once.
Can you please help me?
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
#if NON_REALM
NSLog("FOUND NON_REALM BUILD")
#endif
let bundleID = Bundle.main.bundleIdentifier
NSLog("Loaded bundle id: \(bundleID)")
let controller: FlutterViewController = window?.rootViewController as! FlutterViewController
agentChannel = FlutterMethodChannel(
name: "mobile.cloudbrink/brinkagent",
binaryMessenger: controller.binaryMessenger
)
// Method-channel invocation from Flutter (Dart)
methodChannelInvocationFromUI()
notifyVPNStatusChange()
reInitFlagsBasedOnStatus()
GeneratedPluginRegistrant.register(with: self)
BGTaskScheduler.shared.register(forTaskWithIdentifier: "com.cloudbrink.refresh", using: nil) { task in
self.handleAppRefresh(task: task as! BGAppRefreshTask)
}
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
override func applicationDidEnterBackground(_ application: UIApplication) {
scheduleAppRefresh()
}
func scheduleAppRefresh() {
let request = BGAppRefreshTaskRequest(identifier: "com.cloudbrink.refresh")
request.earliestBeginDate = Date(timeIntervalSinceNow: 15 * 60) // 15 minutes
do {
try BGTaskScheduler.shared.submit(request)
} catch {
print("Could not schedule app refresh: \(error)")
}
}
// Refresh task handler
func handleAppRefresh(task: BGAppRefreshTask) {
print("Before schedule")
scheduleAppRefresh()
print("After schedule")
let queue = OperationQueue()
queue.addOperation {
// Perform your background refresh operation
print("Doing the background task.")
task.setTaskCompleted(success: true)
}
task.expirationHandler = {
queue.cancelAllOperations()
task.setTaskCompleted(success: false)
}
}