【问题标题】:AFNetworking background file uploadAFNetworking后台文件上传
【发布时间】:2014-09-14 01:15:35
【问题描述】:

我想从我的应用程序上传文件到我的服务器。当应用程序处于活动状态时,下面的代码运行良好。如果我按主页按钮或打开另一个应用程序上传停止。

我激活了后台提取但仍然无法正常工作。

Afnetworking 有后台支持,但我不知道如何在我的代码中实现此功能。

NSString *str=[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Archive.zip"];
NSDictionary *parameters = @{@"foo": @"bar"};
     NSURL *filePath = [NSURL fileURLWithPath:str];
    AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];

    NSData *imageData=[NSData dataWithContentsOfURL:filePath];


    NSMutableURLRequest *request =
    [serializer multipartFormRequestWithMethod:@"POST" URLString:@"http://url"
                                    parameters:parameters
                     constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
                         [formData appendPartWithFileData:imageData
                                                     name:@"image"
                                                 fileName:@"Archive.zip"
                                                 mimeType:@"application/zip"];
                     }];


    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    AFHTTPRequestOperation *operation =
    [manager HTTPRequestOperationWithRequest:request
                                     success:^(AFHTTPRequestOperation *operation, id responseObject) {
                                         NSLog(@"Success %@", responseObject);
                                     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                         NSLog(@"Failure %@", error.description);
                                     }];


    [operation setUploadProgressBlock:^(NSUInteger __unused bytesWritten,
                                        long long totalBytesWritten,
                                        long long totalBytesExpectedToWrite) {
        NSLog(@"Wrote %lld/%lld", totalBytesWritten, totalBytesExpectedToWrite);
    }];


    [operation start];

【问题讨论】:

  • 您能找到解决这个问题的方法吗?
  • 从苹果 NSURLSession 文档中,后台传输只支持上传和下载任务(没有数据任务)的文件 URL,根据你的代码看来你正在使用 NSData 上传。

标签: objective-c file-upload afnetworking background-process


【解决方案1】:

改变这一行

[operation start];

到这里

[operation setShouldExecuteAsBackgroundTaskWithExpirationHandler:^{
        // Handle iOS shutting you down (possibly make a note of where you
        // stopped so you can resume later)
    }];


    [manager.operationQueue addOperation:operation];

您可以查看这些链接 AFHTTPRequestOperation doesn't work after stand by modeAlternative for enqueueHTTPRequestOperation in AFNetworking 2.0

【讨论】:

  • 如果应用程序未处于活动状态,它会在几分钟后停止。
  • @charty: 表示应用何时被iOS挂起?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多