AFNetworking后台文件上传

amo*_*one 8 file-upload objective-c background-process afnetworking

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

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

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];
Run Code Online (Sandbox Code Playgroud)

oni*_*ivi 6

改变这一行

[operation start];
Run Code Online (Sandbox Code Playgroud)

对此

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


    [manager.operationQueue addOperation:operation];
Run Code Online (Sandbox Code Playgroud)

您可以查看这些链接 AFHTTPRequestOperation在待机模式后无效,替代用于AFNetworking 2.0中的enqueueHTTPRequestOperation

  • 如果app未激活,它会在几分钟后停止. (5认同)