How to upload a file and save it in the document directory using AFNetworking?

I am using the AFNetworking library. I cannot figure out how to download the file and save it in the document directory.

+49
ios iphone afnetworking
Dec 04 2018-11-12T00:
source share
8 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]; 
+138
Dec 04 2018-11-11T00:
source share

I am going to bounce off @mattt's answer and publish the 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]; 
+31
Dec 05 '13 at 23:08
source share

I'm talking about AFNetworking 2.0

[AFHTTPRequestOperationManager manager] creates a manager object with the default AFJSONResponseSerializer parameter, and it performs content type restrictions. Take a look at this

 - (BOOL)validateResponse:(NSHTTPURLResponse *)response data:(NSData *)data error:(NSError * __autoreleasing *)error 

So, we need to create an absence response serializer and use the AFHTTPRequestOperationManager as usual.

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 

Using

 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 serialization

+5
Jun 11 '14 at 10:04 on
source share

The documentation page contains an example with the section 'Creating a download task':

 NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; NSURL *URL = [NSURL URLWithString:@"http://example.com/download.zip"]; NSURLRequest *request = [NSURLRequest requestWithURL:URL]; NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) { NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil]; return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]]; } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) { NSLog(@"File downloaded to: %@", filePath); }]; [downloadTask resume]; 

NB! Work with iOS 7+ code (verified using AFNetworking 2.5.1)

+4
Feb 13 '15 at 10:45
source share

From AFNetworking docs. Save the downloaded file to your documents. AFNetworking 3.0

 NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; NSURL *URL = [NSURL URLWithString:@"http://example.com/download.zip"]; NSURLRequest *request = [NSURLRequest requestWithURL:URL]; NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) { NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil]; return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]]; } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) { NSLog(@"File downloaded to: %@", filePath); }]; [downloadTask resume]; 
+3
Jun 30 '16 at 7:20
source share
 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; manager.responseSerializer = [AFCompoundResponseSerializer serializer]; manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/octet-stream"]; AFHTTPRequestOperation *operation = [manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) { if (responseObject) { // your code here } else { // your code here } } failure:^(AFHTTPRequestOperation *operation, NSError *error) { }]; [operation start]; 

//manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject: @ "application / octet-stream"]; may vary depending on what you expect

+2
Jan 21 '15 at 5:06
source share

Yes, it is better to use the AFNetworking 2.0 path with the AFHTTPRequestOperationManager . With the previous method, my file was loaded, but for some reason it was not updated on the file system.

By adding swilliam's answer to show the download process, in AFNetworking 2.0 you do the same - just install the download execution block after setting the output stream.

 __weak SettingsTableViewController *weakSelf = self; operation.outputStream = [NSOutputStream outputStreamToFileAtPath:newFilePath append:NO]; [operation setDownloadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToRead) { float progress = totalBytesWritten / (float)totalBytesExpectedToRead; NSString *progressMessage = [NSString stringWithFormat:@"%@ \n %.2f %% \n %@ / %@", @"Downloading ...", progress * 100, [weakSelf fileSizeStringWithSize:totalBytesWritten], [weakSelf fileSizeStringWithSize:totalBytesExpectedToRead]]; [SVProgressHUD showProgress:progress status:progressMessage]; }]; 

This is my method of creating a byte string:

 - (NSString *)fileSizeStringWithSize:(long long)size { NSString *sizeString; CGFloat f; if (size < 1024) { sizeString = [NSString stringWithFormat:@"%d %@", (int)size, @"bytes"]; } else if ((size >= 1024)&&(size < (1024*1024))) { f = size / 1024.0f; sizeString = [NSString stringWithFormat:@"%.0f %@", f, @"Kb"]; } else if (size >= (1024*1024)) { f = size / (1024.0f*1024.0f); sizeString = [NSString stringWithFormat:@"%.0f %@", f, @"Mb"]; } return sizeString; } 
+1
Oct 21 '14 at 3:35
source share

In addition to the previous answers, with AFNetworking 2.5.0 and iOS7 / 8, I found that an extra step to open the output stream is also necessary to prevent the application from freezing (and, ultimately, crashing due to lack of memory).

 operation.outputStream = [NSOutputStream outputStreamToFileAtPath:dest append:NO]; [operation.outputStream open]; [operation start]; 
0
Nov 18 '14 at 23:20
source share



All Articles