iphone - 上传离线数据和上传失败的数据

标签 iphone ios file-upload asihttprequest

我正在将数据发布到服务器(图像和字符串数据)。对于我要上传的每个对象,我在核心数据中都有一个名为“状态”的属性。我在这个属性中输入了3个状态来表示上传状态:上传待处理(还没有尝试上传,或者之前尝试失败),上传处理中(正在上传),上传完成(上传完成,成功)。我有一个计时器检查数据库以上传所有未决数据。

这是处理上传失败数据和离线数据的正确方法吗?

如果这是正确的方法,当尝试上传但用户退出应用程序或当请求超时。有谁知道如何处理这些情况?

顺便说一下,我正在使用 ASIHTTPRequest 作为向服务器发出请求的框架。

详细描述如何以最好的方式做到这一点将获得赏金:)

谢谢!

最佳答案

计时器的想法会奏效。以适合您的应用程序的某个时间间隔通过计时器调用数据管理器类的 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 ]; 

关于iphone - 上传离线数据和上传失败的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8509049/

相关文章:

iphone - iOS - 获取 Info.plist 文件

jquery - JQuery 文件上传演示中限制文件类型

iphone - 奇怪的 UIView 坐标问题

iphone - 使用单独的 xib 文件将 UIView 设计为 tableview 单元格

ios - 由于 ios 中未捕获的异常 'NSUnknownKeyException' 而终止应用程序

amazon-web-services - Spring Boot 多部分文件上传大小不一致

javascript - 如何让 jquery .each 函数与动态元素的 .on ('change' ) 函数一起使用

iphone - 在不使用 initWithContentsOfFile 的情况下将 plist 读取到 NSMutableArray

iOS:创建共享代码的项目

iOS - NSFileHandle availableData 仅当应用程序在设备上手动运行时挂起