【代码笔记】后台运行,可以选择在前台或后台或前后台

一,工程图。

【代码笔记】后台运行,可以选择在前台或后台或前后台_第1张图片

二,代码。

AppDelegate.h

AppDelegate.m

RootViewController.h

复制代码
#import <UIKit/UIKit.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @property (nonatomic, unsafe_unretained) UIBackgroundTaskIdentifier backgroundTaskIdentifier; @property (nonatomic, strong) NSTimer *myTimer; @end
复制代码

 

RootViewController.m

复制代码
#import "AppDelegate.h"
#import "RootViewController.h"

@implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; // Override point for customization after application launch.
 RootViewController *rootVC=[[RootViewController alloc]init]; UINavigationController *nav=[[UINavigationController alloc]initWithRootViewController:rootVC]; self.window.rootViewController=nav; self.window.backgroundColor = [UIColor whiteColor]; [self.window makeKeyAndVisible]; return YES; } - (void)applicationWillResignActive:(UIApplication *)application { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
} - (void)applicationDidEnterBackground:(UIApplication *)application { // 使用这个方法来释放公共的资源、存储用户数据、停止我们定义的定时器(timers)、并且存储在程序终止前的相关信息。 // 如果,我们的应用程序提供了后台执行的方法,那么,在程序退出时,这个方法将代替applicationWillTerminate方法的执行。 // 标记一个长时间运行的后台任务将开始 // 通过调试,发现,iOS给了我们额外的10分钟(600s)来执行这个任务。
    self.backgroundTaskIdentifier =[application beginBackgroundTaskWithExpirationHandler:^(void) { // 当应用程序留给后台的时间快要到结束时(应用程序留给后台执行的时间是有限的), 这个Block块将被执行 // 我们需要在次Block块中执行一些清理工作。 // 如果清理工作失败了,那么将导致程序挂掉 // 清理工作需要在主线程中用同步的方式来进行
 [self endBackgroundTask]; }]; // 模拟一个Long-Running Task
    self.myTimer =[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(timerMethod:) userInfo:nil repeats:YES]; } - (void) endBackgroundTask{ dispatch_queue_t mainQueue = dispatch_get_main_queue(); AppDelegate *weakSelf = self; dispatch_async(mainQueue, ^(void) { AppDelegate *strongSelf = weakSelf; if (strongSelf != nil){ [strongSelf.myTimer invalidate];// 停止定时器 // 每个对 beginBackgroundTaskWithExpirationHandler:方法的调用,必须要相应的调用 endBackgroundTask:方法。这样,来告诉应用程序你已经执行完成了。 // 也就是说,我们向 iOS 要更多时间来完成一个任务,那么我们必须告诉 iOS 你什么时候能完成那个任务。 // 也就是要告诉应用程序:“好借好还”嘛。 // 标记指定的后台任务完成
 [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskIdentifier]; // 销毁后台任务标识符
            strongSelf.backgroundTaskIdentifier = UIBackgroundTaskInvalid; } }); } // 模拟的一个 Long-Running Task 方法
- (void) timerMethod:(NSTimer *)paramSender{ // backgroundTimeRemaining 属性包含了程序留给的我们的时间
    NSTimeInterval backgroundTimeRemaining =[[UIApplication sharedApplication] backgroundTimeRemaining]; if (backgroundTimeRemaining == DBL_MAX){ //前台打印
        NSLog(@"Background Time Remaining = Undetermined"); } else { //后台打印
        NSLog(@"Background Time Remaining = %.02f Seconds", backgroundTimeRemaining); } } - (void)applicationWillEnterForeground:(UIApplication *)application { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. //添加此段代码,则在前台就不运行了。否则会前后台一起运行。除第一次启动的时候,是前台不运行,退出后台时候运行。
    
    if (self.backgroundTaskIdentifier != UIBackgroundTaskInvalid){ [self endBackgroundTask]; } } - (void)applicationDidBecomeActive:(UIApplication *)application { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
} - (void)applicationWillTerminate:(UIApplication *)application { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
} @end
复制代码

 


你可能感兴趣的:(【代码笔记】后台运行,可以选择在前台或后台或前后台)