iOS 程序退到后台长期运行

如果我们想让程序在后台长期运行可以使用block来实现,下面列出实现代码。

声明  UIBackgroundTaskIdentifier 对象

#import "AppDelegate.h"

@interface AppDelegate ()
@property (assign , nonatomic) UIBackgroundTaskIdentifier backgroundUpdateTask;
@end

- (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.
    
    [self beingBackgroundUpdateTask];
}
- (void) beingBackgroundUpdateTask
{
    // 需要长期运行的代码
    for (long i = 0; i < 100000000000; i++) {
       NSLog(@"%ld ....................",i);
    }
    self.backgroundUpdateTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        [self endBackgroundUpdateTask];
    }];
    
}

- (void) endBackgroundUpdateTask
{
    [[UIApplication sharedApplication] endBackgroundTask:self.backgroundUpdateTask];
    self.backgroundUpdateTask = UIBackgroundTaskInvalid;
}


你可能感兴趣的:(iOS)