Reputation: 33
I have a problem, I want to get the file size of my link that i put in my textfield and show it in label before starting the download.
I've done few things and i with [operation.response expectedContentLength]
i just get 0. my code in .m file is this :
NSString *fileName = [self.linkTextBox.stringValue lastPathComponent];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[self.linkTextBox stringValue]]];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
NSLog(@"size :%lld", [operation.response expectedContentLength]);
self.detailText.stringValue = [NSString stringWithFormat:@"%lld", [operation.response expectedContentLength]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:fileName];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];
[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
NSLog(@"bytesRead: %lu, totalBytesRead: %lld, totalBytesExpectedToRead: %lld", (unsigned long)bytesRead, totalBytesRead, totalBytesExpectedToRead);
}];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Successfully downloaded file to %@", path);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
[operation start];
Upvotes: 1
Views: 814
Reputation: 32783
You can send a HEAD
request instead of a GET
one, this will ask the server to send you only the headers for your request. Most servers support this and its the preferable method when you want to obtain some metadata info about the entity you're querying, without having to download it.
The HEAD
request can be achieved by creating a NSMutableURLRequest
and setting the HTTPMethod
property, something like this:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:anURL];
request.HTTPMethod = @"HEAD";
// the rest of the code
This assuming the server developer did his job and he is expecting HEAD
requests and is populating the appropriate http header fields.
Upvotes: 1
Reputation: 54600
You can't get the length before you download, but you can get it as soon as you start to get a response.
You want to use setDownloadProgressBlock:, which is a method on the super class of AFHTTPRequestOperation
which is AFURLConnectionOperation
. The callback has three parameters, the third of which is totalBytesExpectedToRead
.
[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
if (totalBytesExpectedToRead > 0) {
// Do stuff...
}
}];
As others have noted, that value can be 0 if the server doesn't set the content-length header in the HTTP response, so please handle that case.
Upvotes: 0