2011-12-14 74 views
2

我將數據發佈到服務器(圖像和字符串數據)。對於我想上傳的每個對象,我在覈心數據中都有一個名爲「狀態」的屬性。我向此屬性中輸入3個狀態以指示上傳狀態:上傳掛起(尚未嘗試上載,或上次嘗試失敗),上傳處理(當前正在上傳)以及上傳完成(完成上傳,成功)。我有一個計時器,檢查數據庫上傳所有待處理的數據。上傳離線數據和上傳失敗的數據

這是處理上傳失敗數據和脫機數據的正確方法嗎?

如果這是正確的方法,那麼在上傳嘗試但用戶退出應用程序或將用戶退出應用程序時,將上傳狀態從「上傳處理」更改爲「上傳掛起」或「上傳完成」當請求超時。有誰知道如何處理這些情況?

順便說一句,我使用ASIHTTPRequest作爲框架向服務器發出請求。

如何做到這一點的最好辦法將爭取賞金:)

感謝詳細說明!

回答

1

計時器的想法將工作。通過定時器以適合您的應用程序的某個間隔調用數據管理器類的uploadOutstandingObjects

假設您有一個需要上傳的'Foo'實體。您可以在您的數據管理器類中執行以下操作...

- (void)uploadOutstandingObjects { 
    // I use the great MagicalRecord class for Core Data fetching 
    // https://github.com/magicalpanda/MagicalRecord 
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"status == pending"] 
    NSArray *outstandingObjects = [Foo MR_findAllWithPredicate:predicate]; 
    for (Foo *foo in outstandingObjects) { 
      [foo uploadToServer]; 
    } 

要做到這一點的一種方法是使用通知。每當您開始上傳時,您都會讓該對象收聽「uploadsStopped」通知。上傳完成後,上傳的對象將停止監聽。

Foo類:

- (void)uploadFailed { 
    // change status to upload pending in the database for this 'foo' object 
} 
- (void)uploadComplete { 
    // change status to upload complete in the database for this 'foo' object 
} 
-(void)uploadToServer { 
    [[NSNotificationCenter defaultCenter] addObserver:self 
              selector:@selector(uploadFailed:) 
               name:@"uploadsStoppedNotification" 
               object:nil ]; 

    // perform upload. If you are doing this synchronously... 
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:<url here>]; 
    [request startSynchronously]; 
    if (![request error]) { 
     [self uploadSucceeded]; 
     // stop listening to global upload notifications as upload attempt is over 
     [NSNotificationCenter removeObserver:self]; 
    } 
    else { 
     [self uploadFailed]; 
     // stop listening to global upload notifications as upload attempt is over 
     [NSNotificationCenter removeObserver:self]; 
} 

如果您的應用程序退出,你可以處理不斷變化尚未完成

- (void)applicationDidEnterBackground:(UIApplication *)application { 
    // this will fire to any objects which are listening to 
    // the "uploadsStoppedNotification" 
    [[NSNotificationCenter defaultCenter] 
      postNotificationName:@"uploadsStoppedNotification" 
         object:nil ];