我需要在下载前得到文件的大小。并且使用一个进度条
以下是我的代码运行良好,除非文件托管在Hostmonster服务器上,否则我想知道错误是什么。
错误如下: NSConcreteMutableData initWithCapacity::荒谬容量: 4294967295,最大大小: 2147483648字节‘
这是我的密码
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;
}发布于 2013-08-22 18:02:10
expectedContentLength不是无符号值。它的类型是long long,它是签名的。
无符号的4294967295等于有符号的-1.-1表示NSURLResponseUnknownLength.如果返回此值,则响应没有有效的内容大小,http响应并不总是包含内容大小。
在分配NSURLResponseUnknownLength对象时检查是否为NSData。
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是否为零。如果是零,你就把receivedData扔掉了。你应该先查一下零。或者只需在NSMutableData中创建connection:didReceiveResponse:对象
https://stackoverflow.com/questions/18386990
复制相似问题