开发者

How to get document size before downloading that

I want to download a document which i do it by following code

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:str] cachePolicy:NSURLRequestR开发者_C百科eloadIgnoringLocalCacheData timeoutInterval:500];

   [request setHTTPMethod:@"GET"]; 


NSData *returnData =[[NSURL alloc]init];
    returnData=[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

and depending on the data downloaded i want to show progress bar , is there any way how i can do that.

Thanks in advance.


In your delegate of NSURLConnection implement method - (void)connection:(NSURLConnection *)theConnection didReceiveResponse:(NSURLResponse *)response. In this method you can call

long long expLength = [response expectedContentLength];

In expLength you will have expected document size.

But be caution:

Some protocol implementations report the content length as part of the response, but not all protocols guarantee to deliver that amount of data. Clients should be prepared to deal with more or less data.


The NSURLConnection calls its delegate with

- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;

Well, we need to look inside the NSURLResponse, to find the expectedContentLength

- (long long)expectedContentLength   

Return Value The receiver’s expected content length,
or NSURLResponseUnknownLength if the length can’t be determined.


You can do it in either ways using Synchronous/Asynchronous call. For Asynchronous there delegate methods are there which you need to implement in your class and for Synchronous you can call it within your method scope.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜