Skip to content

Instantly share code, notes, and snippets.

@vinnybad
Last active October 3, 2015 20:26
Show Gist options
  • Save vinnybad/dcd5b83c7cdfcf55be9b to your computer and use it in GitHub Desktop.
Save vinnybad/dcd5b83c7cdfcf55be9b to your computer and use it in GitHub Desktop.
Download a file using AFNetworking
/*
* Downloading files using AFNetworking is not a 1-step process, but it's still pretty easy.
*
* NOTE: If you're downloading a file from S3, make sure to set the proper Content-Type. For example,
* a zip file should ideally have the content type of application/zip.
*
* Inspired by various sources online.
*/
#pragma mark - Downloading Files
- (void)downloadFileAtPath:(NSString *)path andOnCompletion:(void (^)(NSURL *fileURL, NSError *error))completionBlock {
NSURL *fileURL = [NSURL URLWithString:path];
if( fileURL ) {
NSURLRequest *request = [NSURLRequest requestWithURL:fileURL];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
NSString *fullPath = [NSTemporaryDirectory() stringByAppendingPathComponent:[fileURL lastPathComponent]];
[operation setOutputStream:[NSOutputStream outputStreamToFileAtPath:fullPath append:NO]];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSError *error = nil;
[[NSFileManager defaultManager] attributesOfItemAtPath:fullPath error:&error];
if (error) {
DLog(@"Error: Couldn't download file at path: %@. Details: %@", path, error );
} else {
if( completionBlock ) {
NSURL *downloadedFileURL = [NSURL fileURLWithPath:fullPath];
completionBlock( downloadedFileURL, error );
}
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
DLog( @"Error: Couldn't download file. Details: %@", error );
if( completionBlock ) {
completionBlock( nil, error );
}
}];
[operation start];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment