您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 技巧大全

iOS 後台處理機制與延後任務實戰

編輯:iOS 技巧大全

當 App 進入後台時,如何妥善處理資源與狀態,直接影響到用戶體驗與 App 的存活率。本文將介紹 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; }

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: 主動告知系統,這樣就能在短暫的後台窗口期內完成清理與保存工作。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved