How to use beginBackgroundTaskWithExpirationHandler for already running task in iOS

前端 未结 6 1517
悲哀的现实
悲哀的现实 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:10

    Take a look at this page, Apple describe how to keep iOS application not suspended while it is in background. Apple Documentation

    And here is what I've implemented:

    UIBackgroundTaskIdentifier bgTask;
    
    - (void)applicationDidEnterBackground:(UIApplication *)application
    {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
        NSLog(@"=== DID ENTER BACKGROUND ===");
        bgTask = [[UIApplication  sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
            NSLog(@"End of tolerate time. Application should be suspended now if we do not ask more 'tolerance'");
            // [self askToRunMoreBackgroundTask]; This code seems to be unnecessary. I'll verify it.
        }];
    
        if (bgTask == UIBackgroundTaskInvalid) {
            NSLog(@"This application does not support background mode");
        } else {
            //if application supports background mode, we'll see this log.
            NSLog(@"Application will continue to run in background");  
        }
    }
    
    /*
    
    - (void)askToRunMoreBackgroundTask
    {
        [[UIApplication sharedApplication] endBackgroundTask:bgTask];
        NSLog(@"restart background long-running task");
        bgTask = [[UIApplication  sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
            NSLog(@"End of tolerate time. Application should be suspended now if we do not ask more 'tolerance'");
            [self askToRunMoreBackgroundTask]; 
        }];
    
    }
    
    */
    
    - (void)applicationWillEnterForeground:(UIApplication *)application
    {
        NSLog(@"=== GOING BACK FROM IDLE MODE ===");
        //it’s important to stop background task when we do not need it anymore
        [[UIApplication sharedApplication] endBackgroundTask:UIBackgroundTaskInvalid];  
    }
    

提交回复
热议问题