Friday, 25 July 2014

Download file or zip using AFNetworking and know the progress

Include AFNetworking in your project

Include below file in your class where you are downloading something


#import "AFNetworking/AFHTTPRequestOperationManager.h"


Use below lines of code for downloading and know progress length


NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http:urPath/act01.zip"]];
        AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
        
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"filename"];
        operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];
        
        [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSLog(@"Successfully downloaded file to %@", path);
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"Error" message:[NSString stringWithFormat:@"%@",error] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil ];
            [alert show];
        }];
        
        [operation start];
        
        [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
            float progress = ((float)totalBytesRead) / totalBytesExpectedToRead;
            NSLog(@"status %f",progress);
           // self.progressView.progress = progress;

        }];