Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AFNetworking background file upload

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];
like image 401
amone Avatar asked Sep 14 '14 01:09

amone


1 Answers

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

like image 146
onivi Avatar answered Sep 24 '22 06:09

onivi