获取大小文件NSURLConnection?

我需要在下载之前获取文件大小。 并使用进度条

这是我的代码运行良好,除非文件托管在Hostmonster服务器上我想知道是什么错误。

错误如下:[NSConcreteMutableData initWithCapacity:]:荒谬容量:4294967295,最大大小:2147483648字节’

这是我的代码

NSURL *url33; NSNumber *filesize; NSMutableData *data2; url33 = [NSURL URLWithString: @ "http://sofzh.miximages.com/ios/enconstruccion."]; - (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; } 

expectedContentLength不是无符号值。 它的类型long long ,有签名。

无符号4294967295等于有符号-1。 -1表示NSURLResponseUnknownLength 。 如果返回此值,则响应没有有效的内容大小,http响应并不总是包含内容大小。

分配NSData对象时检查NSURLResponseUnknownLength

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

当然,如果您不知道内容大小,则无法显示进度条。 在这种情况下,您应该显示不同的进度指示器。 在尝试除以零之前检查0 😉


这段代码也是错误的:

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

首先将数据附加到data2,然后检查data2是否为nil。 如果它是零你只是扔掉了receiveData。 你应该先检查是否为零。 或者只是在connection:didReceiveResponse:创建NSMutableData对象connection:didReceiveResponse: