Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to download a file and save it to the documents directory with AFNetworking?

I am using the AFNetworking library. I can't figure out how to download a file and save it to the documents directory.

like image 593
iamsmug Avatar asked Dec 04 '11 01:12

iamsmug


2 Answers

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"..."]]; AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc] initWithRequest:request] autorelease];  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) {     NSLog(@"Error: %@", error); }];  [operation start]; 
like image 181
mattt Avatar answered Sep 30 '22 09:09

mattt


I'm gonna bounce off @mattt's answer and post a version for AFNetworking 2.0 using AFHTTPRequestOperationManager.

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"filename"];  AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; AFHTTPRequestOperation *op = [manager GET:@"http://example.com/file/to/download"                                 parameters:nil     success:^(AFHTTPRequestOperation *operation, id responseObject) {          NSLog(@"successful download to %@", path);     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {          NSLog(@"Error: %@", error);     }]; op.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO]; 
like image 43
swilliams Avatar answered Sep 30 '22 10:09

swilliams