iOS 后台处理
iOS 后台处理的常见用途
1、进入后台时候删除资源:应用处于挂起状态的时候所占用的资源越少,该应用被iOS终止的风险就越低。通过从内存中清理那些易于重新创建的资源,可以增加应用驻留内存的机会,因此可以大幅加快重启速度。
2、进入后台时候保存状态:保存与用户执行的操作相关的所有信息,这样的话,用户下次回来的时候,依然可以恢复到他们离开时的进度。
3、延时执行,请求更多的后台时间:如果进入后台花费了很多时间,应用可能会从内存中移除,如果应用正在进行文件传输,没有能够完成的话,将会带来很多不便。我们可以将applicationDidEnterBackground 作为平台,告诉系统,你还有额外的工作要做,然后启动一个程序块,真正的执行该工作。
例解:
@property (strong, nonatomic) UILabel *label; @property (strong, nonatomic) UIImage *smiley; @property (strong, nonatomic) UIImageView *smileyView; @property (strong, nonatomic) UISegmentedControl *segmentedControl;
@implementation BIDViewController { BOOL animate; }
- (void)viewDidLoad { [super viewDidLoad]; CGRect bounds = self.view.bounds; CGRect labelFrame = CGRectMake(bounds.origin.x, CGRectGetMidY(bounds) - 50, bounds.size.width, 100); //转动的Label self.label = [[UILabel alloc] initWithFrame:labelFrame]; self.label.font = [UIFont fontWithName:@"Helvetica" size:70]; self.label.text = @"Bazinga!"; self.label.textAlignment = NSTextAlignmentCenter; self.label.backgroundColor = [UIColor clearColor]; //笑脸 CGRect smileyFrame = CGRectMake(CGRectGetMidX(bounds) - 42, CGRectGetMidY(bounds)/2 - 35, 84, 84); self.smileyView = [[UIImageView alloc] initWithFrame:smileyFrame]; self.smileyView.contentMode = UIViewContentModeCenter; NSString *smileyPath = [[NSBundle mainBundle] pathForResource:@"smiley" ofType:@"png"]; self.smiley = [UIImage imageWithContentsOfFile:smileyPath]; self.smileyView.image = self.smiley; //分段器 self.segmentedControl = [[UISegmentedControl alloc] initWithItems: [NSArray arrayWithObjects: @"One", @"Two", @"Three", @"Four", nil]] ; self.segmentedControl.frame = CGRectMake(bounds.origin.x + 20, 50, bounds.size.width - 40, 30); [self.view addSubview:self.segmentedControl]; [self.view addSubview:self.smileyView]; [self.view addSubview:self.label]; NSNumber *indexNumber = [[NSUserDefaults standardUserDefaults] objectForKey:@"selectedIndex"]; if (indexNumber) { NSInteger selectedIndex = [indexNumber intValue]; self.segmentedControl.selectedSegmentIndex = selectedIndex; } //通知 NSNotificationCenter *center = [NSNotificationCenter defaultCenter]; [center addObserver:self selector:@selector(applicationWillResignActive) name:UIApplicationWillResignActiveNotification object:nil]; [center addObserver:self selector:@selector(applicationDidBecomeActive) name:UIApplicationDidBecomeActiveNotification object:nil]; [center addObserver:self selector:@selector(applicationDidEnterBackground) name:UIApplicationDidEnterBackgroundNotification object:nil]; [center addObserver:self selector:@selector(applicationWillEnterForeground) name:UIApplicationWillEnterForegroundNotification object:nil]; }
//Label 向下转动 - (void)rotateLabelDown { [UIView animateWithDuration:0.5 animations:^{ self.label.transform = CGAffineTransformMakeRotation(M_PI); } completion:^(BOOL finished){ [self rotateLabelUp]; }]; } //Label 向上转动 - (void)rotateLabelUp { [UIView animateWithDuration:0.5 animations:^{ self.label.transform = CGAffineTransformMakeRotation(0); } completion:^(BOOL finished){ if (animate) { [self rotateLabelDown]; } }]; }
//离开活动状态 - (void)applicationWillResignActive { NSLog(@"VC: %@", NSStringFromSelector(_cmd)); animate = NO; } //进入活动状态 - (void)applicationDidBecomeActive { NSLog(@"VC: %@", NSStringFromSelector(_cmd)); animate = YES; [self rotateLabelDown]; }
//后台运行 - (void)applicationDidEnterBackground { NSLog(@"VC: %@", NSStringFromSelector(_cmd)); //先获取共享的UIApplication 实例。 UIApplication *app = [UIApplication sharedApplication]; //声明了taskId变量、并用__block修饰。 __block UIBackgroundTaskIdentifier taskId; //告诉系统,需要更多的时间来完成某件事,并承诺在完成之后告诉它。如果系统判定我们运行了太久时间并决定停止运行,可以调用我们做为参数提供的程序块 taskId = [app beginBackgroundTaskWithExpirationHandler:^{ NSLog(@"Background task ran out of time and was terminated."); [app endBackgroundTask:taskId]; }]; //如果系统返回的值是UIBackgroundTaskInvalid,表明系统没有为我们提供任何多余的时间。 if (taskId == UIBackgroundTaskInvalid) { NSLog(@"Failed to start background task!"); return; } // dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSLog(@"Starting background task with %f seconds remaining", app.backgroundTimeRemaining); self.smiley = nil; self.smileyView.image = nil; //存储segmentedControl的位置 NSInteger selectedIndex = self.segmentedControl.selectedSegmentIndex; [[NSUserDefaults standardUserDefaults] setInteger:selectedIndex forKey:@"selectedIndex"]; //模拟一个25秒的过程 [NSThread sleepForTimeInterval:25]; NSLog(@"Finishing background task with %f seconds remaining", app.backgroundTimeRemaining); //告诉系统,我们已经完成 [app endBackgroundTask:taskId]; }); }
//进入前台 - (void)applicationWillEnterForeground { NSLog(@"VC: %@", NSStringFromSelector(_cmd)); NSString *smileyPath = [[NSBundle mainBundle] pathForResource:@"smiley" ofType:@"png"]; self.smiley = [UIImage imageWithContentsOfFile:smileyPath]; self.smileyView.image = self.smiley; }
运行效果: