How to execute a task even when the application is in background or lock mode till it finishes

56 Views Asked by At

Below code i have used to write certain task in background mode.But this executes only for 3mins after it ends task. So i would like to execute particular task till it finishes.

func registerBackgroundTask() {
    backgroundTask = UIApplication.shared.beginBackgroundTask { [weak self] in
        self?.endBackgroundTask()   
    }
    assert(backgroundTask != UIBackgroundTaskInvalid)
}

func endBackgroundTask() {
    print("Background task ended.")
    AppConstants.sharedInstance.scheduleLocalNotification(message: "Background task ended.", title: "status!")
    UIApplication.shared.endBackgroundTask(backgroundTask)
    backgroundTask = UIBackgroundTaskInvalid
}

self.registerBackgroundTask()
self.perform(#selector(self.backgroundTimer(challengeId:)), with: "\(tag)", afterDelay:600)
1

There are 1 best solutions below

0
beshio On

As found in this doc, only pre-defined (by Apple) tasks (in Table 3-1 of the doc) are allowed to run indefinitely. You have no way to execute your task till it finishes. But if you are targeting jail broken devices, you can do it by writing daemon. This seems not the case for you. So, you have no luck.