简体   繁体   中英

Continue getting data in background mode

I am getting data from server and show percentage to user. But when I click to phone home button (I mean my app in background mode. Not kill it) process stops. When I open app again it is continue. What should I do to continue getting data in background mode?

As long as I know, unless your app is playing music or getting position update, the OS won't let your app working in the background for an endless period of time.

You can just tell the OS that your app needs some time to end a task, but generally you won't get more than one ore two minutes more.

Here there is a tutorial for background modes, I hope it can help...

https://www.raywenderlich.com/5817-background-modes-tutorial-getting-started

Make sure you have background modes checked in:

YourApp -> Targets: YourApp -> Signing & Capabilities -> Check background modes

In the ViewDidLoad()

let app = UIApplication.shared

NotificationCenter.default.addObserver(self, selector: #selector(applicationWillResignActive(notification:)), name: UIApplication.willResignActiveNotification, object: app)

NotificationCenter.default.addObserver(self, selector: #selector(didBecomeActive(notification:)), name: UIApplication.didBecomeActiveNotification, object: app)

Under the viewDidLoad you can add this

@objc func applicationWillResignActive(notification: NSNotification){
        print("Entered background")
    }

@objc func didBecomeActive(notification: NSNotification){
        print("Returned to application")
    }

So inside the applicationWillResignActive you can simply call the method to continue the reading.

I hope this is what you were looking for, else I can try to edit it as much as possible.

You can use the below function, it will let your operation run in the background for 2-3 minutes.

  var aBackgroundTask: UIBackgroundTaskIdentifier = UIBackgroundTaskIdentifier.invalid


func registerBackgroundTask() {
        aBackgroundTask = UIApplication.shared.beginBackgroundTask { [weak self] in
              self?.endBackgroundTask()
        }
        assert(callLoggingBackgroundTask != UIBackgroundTaskIdentifier.invalid)
    }


func endBackgroundTask() {
    print("Background task ended.")
    UIApplication.shared.endBackgroundTask(convertToUIBackgroundTaskIdentifier(callLoggingBackgroundTask.rawValue))
    aBackgroundTask = UIBackgroundTaskIdentifier.invalid
}

Call function registerBackgroundTask() when operation starts and call this function endBackgroundTask() when operation finishes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM