Completing a Long-Running Task in the Background(在后台完成长时间运行的任务)

时间:2022-06-08 20:36:48

   当app运行中,按下home键,则此app进入后台,所有操作都将会被中止。若此时有一个需长时间运行的任务尚未结束,则可以向ios借用时间让其在后台继续完成

方法

   - (void)applicationDidEnterBackground:(UIApplication *)application 

   - (UIBackgroundTaskIdentifier)beginBackgroundTaskWithExpirationHandler:(void (^)(void))handler 

   - (void)endBackgroundTask:(UIBackgroundTaskIdentifier)identifier


e.g. --AppDelegate.m文件中

@property (nonatomic, unsafe_unretained) UIBackgroundTaskIdentifier backgroundTaskIdentifier;//请求在后台运行的任务标识(唯一)

@property (nonatomic, strong) NSTimer *myTimer; //用来模拟需长时间运行的操作


- (BOOL) application:(UIApplication *)application

  didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{    

    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];   

    self.window.backgroundColor = [UIColor whiteColor];

    [self.window makeKeyAndVisible];

    return YES;

}

//是否支持多任务处理

- (BOOL) isMultitaskingSupported{    

    BOOL result = NO;

    if ([[UIDevice currentDevice]respondsToSelector:@selector(isMultitaskingSupported)]){

        result = [[UIDevice currentDevice]  isMultitaskingSupported];

    }

    return result;   

}

//进入后台运行,如按home

- (void)applicationDidEnterBackground:(UIApplication *)application{   

    if ([self isMultitaskingSupported] == NO){

        return;

    }   

    self.myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0f

                                                    target:self

                                                  selector:@selector(timerMethod:)

                                                  userInfo:nil

                                                   repeats:YES];

    //向IOS借时间来执行需长时间运行的任务

    self.backgroundTaskIdentifier = [application  beginBackgroundTaskWithExpirationHandler:^(void) {

                                       [self endBackgroundTask]; //必须匹配一个结束任务的操作,来标识此任务运行结束,应用完全进入后台休眠状态

                                    }];    

}

- (void) endBackgroundTask{    

    dispatch_queue_t mainQueue = dispatch_get_main_queue();   

    __weak AppDelegate *weakSelf = self;   

    dispatch_async(mainQueue, ^(void) {

        AppDelegate *strongSelf = weakSelf;

        if (strongSelf != nil){

            [strongSelf.myTimer  invalidate];

            [[UIApplication sharedApplication]  endBackgroundTask:self.backgroundTaskIdentifier];

            strongSelf.backgroundTaskIdentifier =UIBackgroundTaskInvalid;

        }        

    });   

}

- (void) timerMethod:(NSTimer *)paramSender{    

    NSTimeInterval backgroundTimeRemaining = [[UIApplication sharedApplication] backgroundTimeRemaining]; //后台运行时间   

    if (backgroundTimeRemaining ==DBL_MAX){

        NSLog(@"Background Time Remaining = Undetermined");

    } else {

        NSLog(@"Background Time Remaining = %.02f Seconds",

              backgroundTimeRemaining);

    }    

}

//重新点击app应用图标,进入前台

- (void)applicationWillEnterForeground:(UIApplication *)application{   

    if (self.backgroundTaskIdentifier != UIBackgroundTaskInvalid){

        [self endBackgroundTask];

    }    

}