當 App 進入後台時,如何妥善處理資源與狀態,直接影響到用戶體驗與 App 的存活率。本文將介紹 iOS 後台處理的常見用途,並透過一個完整示例演示如何申請額外的後台執行時間。
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; }
viewDidLoad 中佈置界面並註冊通知:
- (void)viewDidLoad { [super viewDidLoad]; CGRect bounds = self.view.bounds; CGRect labelFrame = CGRectMake(bounds.origin.x, CGRectGetMidY(bounds) - 50, bounds.size.width, 100); 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]; }]; } - (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 *app = [UIApplication sharedApplication]; __block UIBackgroundTaskIdentifier taskId; taskId = [app beginBackgroundTaskWithExpirationHandler:^{ NSLog(@"Background task ran out of time and was terminated."); [app endBackgroundTask:taskId]; }]; 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; NSInteger selectedIndex = self.segmentedControl.selectedSegmentIndex; [[NSUserDefaults standardUserDefaults] setInteger:selectedIndex forKey:@"selectedIndex"]; [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; }
運行效果:

關鍵在於透過 beginBackgroundTaskWithExpirationHandler: 向系統申請額外時間,並在完成後調用 endBackgroundTask: 主動告知系統,這樣就能在短暫的後台窗口期內完成清理與保存工作。