Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
460 views
in Technique[技术] by (71.8m points)

ios - Objective-c Check file size from URL without downloading

I need to check the size of file from a URL. I get the file size perfectly when downloading file with AFNetworking.

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

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

                                                                        }];

and get file size in another block

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

    }];

But i need to check file size before initiating download request, so that i can prompt to user. I have 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 UI, coz it download all data to calculate its size. Is there any way to check file size before downloading? Any help is appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If the server supports it you can make a request to just get the headers (HEAD, as opposed to GET) without the actual data payload and this should include the Content-Length.

If you can't do that then you need to start the download and use expectedContentLength of the NSURLResponse.


Basically, create an instance of NSMutableURLRequest and call setHTTPMethod: with the method parameter set to @"HEAD" (to replace the default which is GET). Then send that to the server as you currently request for the full set of data (same URL).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...