objective-c - AFNetworking后台文件上传

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

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

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

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];

最佳答案

改变这一行

[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

关于objective-c - AFNetworking后台文件上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25829236/

相关文章:

java - 如何使用JSP、Java(Struts.)上传dat文件?

上传图像文件的javascript/jquery大小和尺寸

ios - 使用 AFNetworking 2 和可达性没有互联网连接警报

ios - 找不到 AFNetworking 文件

objective-c - 防止捏合手势缩小到原始框架之外

ios - 越界异常

Node.js 无法读取 XHR2 FormData 数据

ios - 专为 iOS7 设计的 Storyboard 在 4 英寸设备的 iOS 6 上无法全屏显示

ios - 滚动时 UITableview 滞后。

ios - 如何同步检查互联网连接?