How to Download a File and Save It to the Documents Directory with Afnetworking

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


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

AFNetworking - saving a downloaded file

Yes make sure that u have used correct path into NSOutputStream

Add this:

[_operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Successfully downloaded file");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
[_operation start];

Download a file / image with AFNetworking in iOS?

You have a few problems here. so first, why are you using @autoreleasepool? i think there is no need for this here. also, are you using ARC? i consider this, for the rest of my answer.

in AFNetworking there is a class called AFImageRequestOperation , so this would be a good idea for you to use. first, import it

#import "AFImageRequestOperation.h"

then you could create an object

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:photourl]];
AFImageRequestOperation *operation;
operation = [AFImageRequestOperation imageRequestOperationWithRequest:request
imageProcessingBlock:nil
cacheName:nil
success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {

}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
NSLog(@"%@", [error localizedDescription]);
}];

now, in the success block, you got the UIImage you need.
there you need to get the documents directory. your code will not work on an ios device.

// Get dir
NSString *documentsDirectory = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
documentsDirectory = [paths objectAtIndex:0];
NSString *pathString = [NSString stringWithFormat:@"%@/%@",documentsDirectory, guideName];

and then you could use NSDatas writeToFile

// Save Image
NSData *imageData = UIImageJPEGRepresentation(image, 90);
[imageData writeToFile:pathString atomically:YES];

at last, you need to start the operation

[operation start];

all together:

- (void)downloadImageInBackground:(NSDictionary *)args{

NSString *guideName = [args objectForKey:@"guideName"];
NSString *photourl = [args objectForKey:@"photoUrl"];

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:photourl]];

AFImageRequestOperation *operation = [AFImageRequestOperation imageRequestOperationWithRequest:request
imageProcessingBlock:nil
cacheName:nil
success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {

// Get dir
NSString *documentsDirectory = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
documentsDirectory = [paths objectAtIndex:0];
NSString *pathString = [NSString stringWithFormat:@"%@/%@",documentsDirectory, guideName];

// Save Image
NSData *imageData = UIImageJPEGRepresentation(image, 90);
[imageData writeToFile:pathString atomically:YES];

}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
NSLog(@"%@", [error localizedDescription]);
}];

[operation start];
}

AFNetworking make the same download for different files

Thanks this man Till

I have made this class below that solves my problem:

#import "NetworkManager.h"
#import "AFHTTPRequestOperation.h"

typedef void (^NetworkManagerBlock)(void);

@implementation NetworkManager

- (NSString *)fileNameFromUrlString:(NSString *)urlString
{
NSArray *components = [urlString componentsSeparatedByString:@"/"];
return [components lastObject];
}

- (void)downloadFileWithUrlString:(NSString *)urlString withCompletionBlock:(NetworkManagerBlock)block
{
NSURL *url = [NSURL URLWithString:urlString];

NSURLRequest *request = [NSURLRequest requestWithURL:url];

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *fileName = [self fileNameFromUrlString:urlString];
NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:fileName];

operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

block();

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

NSLog(@"Error: %@", error);

}];

[operation start];
}

- (void)downloadUpadatesPlistWithUrlString:(NSString *)urlString
{
NetworkManagerBlock block = ^ {
[self fetchZipFilesFromUpdatesPlistFile];
};

[self downloadFileWithUrlString:urlString withCompletionBlock:block];
}

- (void)fetchZipFilesFromUpdatesPlistFile
{
NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

NSString* filePath = [documentsPath stringByAppendingPathComponent:@"updates.plist"];

NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:filePath];

for (NSDictionary *item in [dict objectForKey:@"updates"]) {
[self downloadZipFileWithUrlString:[item objectForKey:@"url"]];
}
}

- (void)downloadZipFileWithUrlString:(NSString *)urlString
{
NetworkManagerBlock block = ^ {
NSLog(@"ZIP file loaded");
};

[self downloadFileWithUrlString:urlString withCompletionBlock:block];
}

@end

What's about clean code or readability? What do you think? Maybe you have advice or comments.



Related Topics



Leave a reply



Submit