0
在我的iOS應用程序中,我在後臺線程中下載了相當大量的數據。我需要做的是以某種方式檢查用戶何時重新打開應用程序,如果此任務仍在運行或者它已被取消。知道GCD線程是否正在運行
例如,如果用戶點擊主頁按鈕,然後回到應用程序,線程將繼續這是很好的。但是如果線程被操作系統破壞了會怎樣。如何在應用程序恢復時知道線程是否正在運行。
謝謝!
一些代碼:
// Starts a background thread and also allows it to run in the background if the user exits app
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
UIBackgroundTaskIdentifier bgTask = 0;
bgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
[self endBackgroundUpdateTask:bgTask];
}];
// Code here to run in background
// Tell the main thread its done, and also remove itself from background execution
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"Done with background thread");
[self endBackgroundUpdateTask:bgTask];
});
是的,這是真的,但看看我發佈的代碼。我已經使用beginBackgroundTaskWithExpirationHandler,並且工作正常。但是說這項任務需要比系統提供的更長的時間。那麼它會優雅地關閉線程。當用戶再次打開該應用程序時,我想檢查它是否被擊落,以便我可以再次開始下載。 – Eric
好的,那麼..它相當簡單的使用:backgroundTimeRemaining來檢查你試圖完成時剩下多少時間。當它失敗時,很明顯你不會做到這一點。保存狀態,設置一個標誌,您需要在下次啓動時繼續下載並調用endBackgroundUpdateTask。真的沒有其他辦法。 –