您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

讓 iOS App 長期留在背景:UIBackgroundTask 的接力寫法與風險

編輯:iOS 相關資訊

先說結論:這篇文章記錄的是一個非官方途徑的做法,能讓 App 在 iOS 上長時間滯留背景。它確實可行,但同時踩了兩條蘋果的紅線——濫用背景模式,以及用不當手段規避系統終止機制。實務上請勿用於提交 App Store 的正式版本,以下純為原理記錄。

思路

iOS 對背景執行有嚴格限制。一般 App 進入背景後,系統會給一段有限時間收尾,時間到就強制終止。而這段時間的長度,會因為你宣告的背景模式而有所不同。

這個做法分兩半:

  1. 在 Info.plist 的 Required background modes 中加入 App provides Voice over IP services,讓系統給予較長的執行時間。
  2. 在 App 進入背景時開啟一個 background task,並用 timer 週期性地「結束舊任務、同時開新任務」,讓計時器不斷被重置,App 就不會被判時限已到。

Info.plist 設定

<key>UIBackgroundModes</key>
<array>
    <string>voip</string>
</array>

Delegate 中的實作

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(並留下「未正確結束背景任務」的崩潰日誌)。

為什麼不建議這樣做

  • App Store 審核會被拒。VoIP 背景模式在審核時會被要求說明實際用途,若 App 並非網路電話,幾乎必然被拒;「持續定位」與「背景音訊」同理。
  • 系統會回收。後續 iOS 版本對背景執行時間與背景任務數量都收得更緊,低記憶體時 App 仍會被強制終止,這種接力寫法並不可靠。
  • 電量與效能代價。長期背景執行會被系統標記為高耗電 App,使用者那邊就是電量掉得比別人快。
  • 不是所有需求都需要背景執行。若目的只是「資料要更新」,正確答案是背景 App 重新整理(Background App Refresh)、Silent Push、或 URLSession 的背景上傳/下載——這些都能讓系統在你的 App 未執行時替你完成工作,而且完全合法。

換句話說,如果你的目標是「讓某件事在 App 不在前景時持續發生」,先問那是什麼事:檔案傳輸用背景 URLSession,伺服器要通知你就用遠端推送,需要定期拉資料就用 Background Tasks 框架。這些才是能安全送審的路。

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