先說結論:這篇文章記錄的是一個非官方途徑的做法,能讓 App 在 iOS 上長時間滯留背景。它確實可行,但同時踩了兩條蘋果的紅線——濫用背景模式,以及用不當手段規避系統終止機制。實務上請勿用於提交 App Store 的正式版本,以下純為原理記錄。
iOS 對背景執行有嚴格限制。一般 App 進入背景後,系統會給一段有限時間收尾,時間到就強制終止。而這段時間的長度,會因為你宣告的背景模式而有所不同。
這個做法分兩半:
App provides Voice over IP services,讓系統給予較長的執行時間。
<key>UIBackgroundModes</key>
<array>
<string>voip</string>
</array>
UIBackgroundTaskIdentifier backgroundTaskIdentifier;
UIBackgroundTaskIdentifier oldBackgroundTaskIdentifier;
- (BOOL)isMultitaskingSupported {
BOOL result = NO;
if ([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)]) {
result = [[UIDevice currentDevice] isMultitaskingSupported];
}
return result;
}
- (void)timerMethod:(NSTimer *)paramSender {
count++;
if (count % 500 == 0) {
UIApplication *application = [UIApplication sharedApplication];
// 開啟一個新的後台任務
backgroundTaskIdentifier =
[application beginBackgroundTaskWithExpirationHandler:^{}];
// 結束舊的後台任務
[application endBackgroundTask:backgroundTaskIdentifier];
oldBackgroundTaskIdentifier = backgroundTaskIdentifier;
}
NSLog(@"%ld", count);
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
if ([self isMultitaskingSupported] == NO) {
return;
}
// 開啟一個後台任務
backgroundTaskIdentifier =
[application beginBackgroundTaskWithExpirationHandler:^{}];
oldBackgroundTaskIdentifier = backgroundTaskIdentifier;
if ([self.myTimer isValid]) {
[self.myTimer invalidate];
}
self.myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self selector:@selector(timerMethod:)
userInfo:nil repeats:YES];
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
if (backgroundTaskIdentifier != UIBackgroundTaskInvalid) {
[application endBackgroundTask:backgroundTaskIdentifier];
if ([self.myTimer isValid]) {
[self.myTimer invalidate];
}
}
}
beginBackgroundTaskWithExpirationHandler: 會向系統「借」一段背景執行時間,並回傳一個識別碼。若時間快到而任務還沒結束,系統會呼叫 expiration handler 再把 App 終止。
關鍵在 timer:每隔一段時間就重新 begin 一個新任務並 end 掉舊的,等於不斷把時限重置。回到前景時則必須把任務結束、timer 註銷,否則系統會因為任務未正確收尾而直接終止 App(並留下「未正確結束背景任務」的崩潰日誌)。
URLSession 的背景上傳/下載——這些都能讓系統在你的 App 未執行時替你完成工作,而且完全合法。換句話說,如果你的目標是「讓某件事在 App 不在前景時持續發生」,先問那是什麼事:檔案傳輸用背景 URLSession,伺服器要通知你就用遠端推送,需要定期拉資料就用 Background Tasks 框架。這些才是能安全送審的路。