2011-12-14 78 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 ];