get size file NSURLConnection?

2019-06-03 02:28发布

问题:

I need to get the file size before downloading. And using a progressbar

here is my code works well unless if the file is hosted on Hostmonster server I would like to know what is the error.

The error is as follows: [NSConcreteMutableData initWithCapacity:]: absurd capacity: 4294967295, maximum size: 2147483648 bytes'

Here is my code

NSURL *url33;
NSNumber *filesize;
NSMutableData *data2;

url33 = [NSURL URLWithString: @ "http://www.nordenmovil.com/enconstruccion.jpg"];

- (void)connection: (NSURLConnection*) connection didReceiveResponse: (NSHTTPURLResponse*) response
{
   filesize = [NSNumber numberWithUnsignedInteger:[response expectedContentLength]];
    NSLog(@"%@",filesize);
}


- (void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)recievedData {
    [data2 appendData:recievedData];

    if (data2==nil) {
        data2 = [[NSMutableData alloc] initWithCapacity:[filesize floatValue]];
    }

    NSNumber *resourceLength = [NSNumber numberWithUnsignedInteger:[data2 length]]; //MAGIC
    float progress = [resourceLength floatValue] / [filesize floatValue];
    progressBar.progress = progress;
}

回答1:

expectedContentLength is not an unsigned value. Its type is long long, which is signed.

An unsigned 4294967295 is equal to a signed -1. And -1 means NSURLResponseUnknownLength. If this value is returned the response does not have a valid content size, a http response does not always contain a content size.

Check for NSURLResponseUnknownLength when allocating your NSData object.

if ([response expectedContentLength] == NSURLResponseUnknownLength) {
    // unknown content size
    fileSize = @0;
}
else {
    fileSize = [NSNumber numberWithLongLong:[response expectedContentLength]];
}

and of course, if you don't know the content size you can't show a progress bar. In this case you should show a different progress indicator. Check for 0 before you try to divide by zero ;-)


And this code is wrong too:

[data2 appendData:recievedData];

if (data2==nil) {
    data2 = [[NSMutableData alloc] initWithCapacity:[filesize floatValue]];
}

You first append data to data2, and after that you check if data2 is nil. If it is nil you just threw away receivedData. You should check for nil first. Or just create the NSMutableData object in connection:didReceiveResponse: