AFNetworking 后台文件上传

8

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

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

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

你能找到解决这个问题的方法吗? - Shumais Ul Haq
从苹果的NSURLSession文档中可以看出,后台传输仅支持使用文件URL上传和下载任务(不支持数据任务)。根据您的代码,似乎您正在使用NSData上传。 - vnaren001
1个回答

6

5
如果应用程序未处于活动状态,几分钟后它会停止。 - amone
@charty:意味着当应用程序被iOS挂起时? - BaSha

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接