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];
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];
I'm talking about AFNetworking 2.0
[AFHTTPRequestOperationManager manager]
creates manager object with default AFJSONResponseSerializer, and it performs content types restriction. Take a look at this
- (BOOL)validateResponse:(NSHTTPURLResponse *)response data:(NSData *)data error:(NSError * __autoreleasing *)error
So we need to create a none response serializer and use AFHTTPRequestOperationManager
as normal.
Here is the AFNoneResponseSerializer
@interface AFNoneResponseSerializer : AFHTTPResponseSerializer+ (instancetype)serializer;@end@implementation AFNoneResponseSerializer#pragma mark - Initialization+ (instancetype)serializer{ return [[self alloc] init];}- (instancetype)init{ self = [super init]; return self;}#pragma mark - AFURLResponseSerializer- (id)responseObjectForResponse:(NSURLResponse *)response data:(NSData *)data error:(NSError *__autoreleasing *)error{ return data;}@end
Usage
self.manager = [AFHTTPRequestOperationManager manager];self.manager.responseSerializer = [AFNoneResponseSerializer serializer];[self.manager GET:@"https://sites.google.com/site/iphonesdktutorials/xml/Books.xml" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) { if (success) { success(responseObject); } } failure:^(AFHTTPRequestOperation *operation, NSError *error) { if (failure) { failure(error); } }];
so that we can get the whole file without any serialization