Continue operation when app did enter background on iOS

后端 未结 1 881
南方客
南方客 2020-12-15 00:30

in my app i have some NSOperation that update some core data element from a online database, sometime the update require some minute, and when the screen of iPhone lock, the

相关标签:
1条回答
  • 2020-12-15 00:56

    That's not how you do this. Any code that you want to run in the background must be wrapped properly. Something like this:

    - (void)someMethodToKeepRunningInBackground {
        UIBackgroundTaskIdentifier taskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^(void) {
            // Uh-oh - we took too long. Stop task.
        }];
    
        // Perform task here        
    
        if (taskId != UIBackgroundTaskInvalid) {
            [[UIApplication sharedApplication] endBackgroundTask:taskId];
        }
    }
    

    You don't do anything in the UIApplicationDelegate applicationDidEnterBackground: method.

    Any task that is wrapped inside the "background task" calls will be allowed to keep running when the app enters the background.

    Here's the really important part - the task only gets 10 minutes maximum. If it is still running after 10 minutes your app will be terminated. The expiration handler gives you a few seconds to cleanly end the task before the app is terminated uncleanly.

    0 讨论(0)
提交回复
热议问题