File Upload using AFNetworking in iOS application.


If developing a app at times you are required to upload files. As i got stuck many times so i thought about writing most common way of uploading.
[Join Like Minded and helpful group of iOS developers on FACEBOOK]
Prerequisites :-

1. Get latest AFNetworking library Link 

Suggestion:-  I very strongly recommend that you first check the post service using a good REST client from Firefox or Chrome. You don't want to bang your head over a nonworking API.

Now once you have tested your API using any REST client i suppose you have

1. Base URL  e.g http:// <your domain>.com
2.Path             eg  /first/second
3.Header field key value pair e.g.  "Source" : "web"
4.Parameter key value pair     e.g.  "action_name" :"postimage"

now here is a simple function just go through it and understand.

    //the image name is Denise.jpg i have uses image you can youse any file
    //just convert it to nsdat in an appropriateway
    UIImage *image= [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Denise" ofType:@"jpg"]];
    //  getting data from image
    NSData *photoData= UIImagePNGRepresentation(image);
    // making AFHttpClient
    AFHTTPClient *client= [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:@"http://<your domain>.com/"]];
    //setting headers
    [client setDefaultHeader:@"multipart/form-data; charset=utf-8; boundary=0xKhTmLbOuNdArY" value:@"Content-Type"];
    [client setDefaultHeader:@"source" value:@"web"];
     NSMutableURLRequest *request1 = [client multipartFormRequestWithMethod:@"POST" path:@"application/uploadfile" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
    //setting body
        [formData appendPartWithFormData:[[NSString stringWithFormat:@"signup"] dataUsingEncoding:NSUTF8StringEncoding] name:@"action_name"];
        [formData appendPartWithFormData:[[NSString stringWithFormat:@"28"] dataUsingEncoding:NSUTF8StringEncoding] name:@"id"];
        [formData appendPartWithFileData:photoData name:@"file_data" fileName:@"file.png" mimeType:@"image/png"];
    [request1 setTimeoutInterval:180];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request1];
    [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
        NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
        float progress = totalBytesWritten / (float)totalBytesExpectedToWrite;
    // use this float value to set progress bar.
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
         NSDictionary *jsons = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
         NSLog(@"response headers: %@", [[operation response] allHeaderFields]);
         NSLog(@"response: %@",jsons);
                                     failure:^(AFHTTPRequestOperation *operation, NSError *error)
         if([operation.response statusCode] == 403)
             NSLog(@"Upload Failed");
         NSLog(@"error: %@", [error debugDescription]);
    [operation start];


USING :-AFHTTPRequestOperationManager

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer=[AFJSONRequestSerializer serializer];
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=0xKhTmLbOuNdArY"];
    [manager.requestSerializer setValue:contentType forHTTPHeaderField:@"Content-Type"];
    [manager.requestSerializer setValue:<your value> forHTTPHeaderField:<header feild>];
    [manager POST:<URL STRING>parameters:@{<dictionary of parameters>} constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        NSString  *name=<file name>;
        [formData appendPartWithFileURL:<file path document directory/you can also used data directly> name:name fileName:fileName mimeType:@"image/png" error:nil];
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[Join Like Minded and helpful group of iOS developers on FACEBOOK]