2

I have these methods that handle a download

But there is an error when initialize NSMutableData

NSNumber *filesize;
NSMutableData *data;

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    filesize = [NSNumber numberWithUnsignedInteger:[response expectedContentLength]];

}

- (void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)recievedData {


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


    [data appendData:recievedData];
    NSNumber *resourceLength = [NSNumber numberWithUnsignedInteger:[data length]]; //MAGIC
    float progress = [resourceLength floatValue] / [filesize floatValue];
    progressBar.progress = progress;



}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{

    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error "
                                                        message:@" " delegate:self cancelButtonTitle: @"OK"
                                              otherButtonTitles:nil];
    [alertView show];

    connection1=nil;
    [connection1 cancel];



}

- (void)connectionDidFinishLoading:(NSURLConnection*)theConnection {

}

Here generates error

data = [[NSMutableData alloc] initWithCapacity:[filesize floatValue]];

[NSConcreteMutableData initWithCapacity:]: absurd capacity: 4294967295, maximum size: 2147483648 bytes'

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Fabio
  • 1,913
  • 5
  • 29
  • 53

1 Answers1

3

If NSURLResponse expectedContentLength doesn't know the length, it will return -1 (the documentation says NSURLResponseUnknownLength, which is a constant initialized to -1).

You then use a funny way to go from long long (result type of NSURLResponse expectedContentLength) via NSNumber numberWithUnsignedInteger and NSNumber floatValue to NSUInteger (argument to NSMutableData initWithCapacity:). The result is that -1 (internally represented as 0xffffffff) ends up as 4294967295 (internally represented as 0xffffffff as well).

You have to test for NSURLResponseUnknownLength and use a different initial capacity in that case. And don't use NSNumber. Simply convert the signed long long into an unsigned NSUInteger if it's within the reasonable range.

Codo
  • 75,595
  • 17
  • 168
  • 206