2012-07-07 102 views
1

我想上傳一些應該繼續下去的文件,即使應用程序進入後臺。NSOperation和NSOperationQueue的後臺任務iOS

目前我正在從數據庫中檢索文件,並通過NSOperation將其添加到隊列中,然後啓動上載過程。

即使應用程序轉到後臺或前臺,也應該上傳所有文件。 下面是單個任務的代碼,任何人都可以給我一個提示,我們如何使它可以上傳許多文件。

UIApplication* application = [UIApplication sharedApplication]; 
bgTask = [application beginBackgroundTaskWithExpirationHandler:^{ 
    // Clean up any unfinished task business by marking where you 
    // stopped or ending the task outright. 

    [application endBackgroundTask: bgTask]; 
    bgTask = UIBackgroundTaskInvalid; 
}]; 

回答

0

爲什麼不嘗試這樣做呢? ..我還沒有嘗試過了,我會嘗試此

UIApplication* application = [UIApplication sharedApplication]; 
bgTask = [application beginBackgroundTaskWithExpirationHandler:^{ 
    // Clean up any unfinished task business by marking where you 
    // stopped or ending the task outright. 

    // Bring up your NSOperation queue instance here and block this thread until it is complete 
    [queue waitUntilAllOperationsAreFinished]; 

    [application endBackgroundTask: bgTask]; 
    bgTask = UIBackgroundTaskInvalid; 
}]; 

後發佈的更新也保證你有辦法取消在後臺所有這些長期運行

bgTask = [application beginBackgroundTaskWithExpirationHandler:^{ 
     // Clean up any unfinished task business by marking where you. 
     // stopped or ending the task outright. 
     [queue cancelAllOperations]; 

     [application endBackgroundTask:endSessionTask]; 
     bgTask = UIBackgroundTaskInvalid; 
    }]; 
+1

我不認爲這個答案是正確的。 'waitUntilAllOperationsAreFinished'調用應該在'beginBackgroundTaskWithExpirationHandler'之後進行,而不是在expiration塊內。看到這個答案:http://stackoverflow.com/questions/10319643/objective-c-proper-use-of-beginbackgroundtaskwithexpirationhandler – Dima 2014-12-08 22:32:01