Search code examples
iosswiftswift3

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?


Solution

  • 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.