How to use beginBackgroundTaskWithExpirationHandler for already running task in iOS

前端 未结 6 1518
悲哀的现实
悲哀的现实 2020-11-28 03:10

In my app, I am uploading images to server from iPhone. While sync if user press home button, App will close.

I want app must be running in background till sync fini

6条回答
  •  我在风中等你
    2020-11-28 04:00

    Here's a slight variation on the other answers which I'm using when the app is going to the background and I need to do something on the main thread:

    - (void)applicationWillResignActive:(UIApplication *)application
    {
         UIApplication *app = [UIApplication sharedApplication];
    
        // Register auto expiring background task
        __block UIBackgroundTaskIdentifier bgTaskId =
            [app beginBackgroundTaskWithExpirationHandler:^{
            [app endBackgroundTask:bgTaskId];
            bgTaskId = UIBackgroundTaskInvalid;
        }];
    
        // Execute background task on the main thread
        dispatch_async( dispatch_get_main_queue(), ^{
            // ------------------
            // DO SOMETHING INVOLVING THE WEBVIEW - WHICH MUST OCCUR ON THE MAIN THREAD!
            // ------------------
            [app endBackgroundTask:bgTaskId];
            bgTaskId = UIBackgroundTaskInvalid;
        });
    }
    

提交回复
热议问题