AFNetworking background file upload

2019-02-09 07:56发布

I want to upload files to my server from my app. The code below is working great when app is active. If I press home button or open another app uploading stops.

I activated background fetch but still not working.

Afnetworking has background support but I cant figure out how I implement this feature to my code.

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

1条回答
太酷不给撩
2楼-- · 2019-02-09 08:36

Change this line

[operation start];

to this

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


    [manager.operationQueue addOperation:operation];

You can look at these links AFHTTPRequestOperation doesn't work after stand by mode and Alternative for enqueueHTTPRequestOperation in AFNetworking 2.0

查看更多
登录 后发表回答