Objective-c Check file size from URL without loading

I need to check file size from url. I get the file size perfectly when uploading a file using AFNetworking.

AFHTTPRequestOperation *operation = [client HTTPRequestOperationWithRequest:request
                                                                        success:^(AFHTTPRequestOperation *operation, id responseObject) {
                                                                            // Success Callback

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

                                                                        }];

and get the file size in another block

[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {

    }];

But I need to check the file size before running the download request so that I can request the user. I also tried another method

NSURL *url = [NSURL URLWithString:@"http://lasp.colorado.edu/home/wp-content/uploads/2011/03/suncombo1.jpg"];
NSData *data = [NSData dataWithContentsOfURL:url];
NSLog(@"original = %d", [data length]);

But it blocks the user interface because it loads all the data to calculate its size. Is there a way to check the file size before downloading? Any help is appreciated.

+4
source share
2 answers

, , (HEAD, GET) , Content-Length.

, expectedContentLength NSURLResponse.


NSMutableURLRequest setHTTPMethod: method, @"HEAD" ( GET). , ( URL).

+21

:

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:candidateURL];
                    [request setHTTPMethod:@"HEAD"];

                    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
                    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
                     {
                         NSLog(@"Content-lent: %lld", [operation.response expectedContentLength]);

                     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                         NSLog(@"Error: %@", error);
                     }];
+6

All Articles