Is it possible to start BackgroundTask again when the previous task is over

Viewed 814

I use UIBackgroundTaskIdentifier to begin background task in my app. When ı use a IOS device (IOS 11.3) takes about 3 minutes. When ı use the other IOS device (IOS 13.4.1) takes about 30 seconds. This my code give in below;

var threadStarted = false
var backgroundTask : UIBackgroundTaskIdentifier = UIBackgroundTaskIdentifier.invalid

func extendBackgroundRunningTime() {
        if (self.backgroundTask != UIBackgroundTaskIdentifier.invalid) {
            // if we are in here, that means the background task is already running.
            // don't restart it.
            return
        }

        print("Attempting to extend background running time")

        self.backgroundTask = UIApplication.shared.beginBackgroundTask(withName: "DummyTask1", expirationHandler: {
            print("Background Time:\(UIApplication.shared.backgroundTimeRemaining)")
            UIApplication.shared.endBackgroundTask(self.backgroundTask)
            self.backgroundTask = UIBackgroundTaskIdentifier.invalid
            self.extendBackgroundRunningTime()

        })

        if threadStarted {
            print("Background task thread already started.")
        }
        else {
            threadStarted = true
            DispatchQueue.global(priority: DispatchQueue.GlobalQueuePriority.default).async {
                while (true) {
                    // A dummy tasks must be running otherwise iOS suspends immediately
                    Thread.sleep(forTimeInterval: 1);
                }
            }
        }
    }

Please let me know is it possible to extend the working time of background. I get ;

" [BackgroundTask] Background task still not ended after expiration handlers were called: <UIBackgroundTaskInfo: 0x2812d6440>: taskID = 1, taskName = DummyTask1, creationTime = 52268 (elapsed = 0), assertion = . This app will likely be terminated by the system. Call UIApplication.endBackgroundTask(:) to avoid this."

and stop task.

0 Answers
Related