We can solve this by using background task and runloop mechanism.

Below piece of code can save your day for problem like run app in background continue.  

Initialise var UIBackgroundTaskIdentifier

       var bgTask:UIBackgroundTaskIdentifier!

        bgTask = application.beginBackgroundTaskWithName(“MyTask”, expirationHandler: {() -> Void in

            // Clean up any unfinished task business by marking where you

            // stopped or ending the task outright.

            application.endBackgroundTask(self.bgTask)

            self.bgTask = UIBackgroundTaskInvalid

        })

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {() -> Void in

            // Do the work associated with the task, preferably in chunks.

Here 60 * 5 is define your interval to do something in background , 60*5 = 5 minutes

             self.timer = NSTimer.scheduledTimerWithTimeInterval(60 * 5, target: self, selector:                                #selector(AppDelegate.handleTimer(_:)), userInfo: nil, repeats: true)

            application.endBackgroundTask(self.bgTask)

            self.bgTask = UIBackgroundTaskInvalid

            NSRunLoop.currentRunLoop().addTimer(self.timer, forMode: NSDefaultRunLoopMode)

            NSRunLoop.currentRunLoop().run()

        })

Handler function

    func handleTimer(timer: NSTimer) {

Do whatever you want in background mode of application.

       }

Limitation is if you put app interval more than 15 minutes than Application forcefully put in suspended mode by iOS.

You may also like

Leave a Reply