我有这些处理下载的方法
但初始化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 {
}
此处生成错误
data = [[NSMutableData alloc] initWithCapacity:[filesize floatValue]];
[NSConcreteMutableData initWithCapacity:]:荒谬容量:4294967295,最大大小:2147483648字节'
答案 0 :(得分:3)
如果NSURLResponse expectedContentLength
不知道长度,它将返回-1(文档说NSURLResponseUnknownLength
,这是一个初始化为-1的常量。)
然后,您可以使用一种有趣的方式从long long
(NSURLResponse expectedContentLength
的结果类型)到NSNumber numberWithUnsignedInteger
和NSNumber floatValue
到NSUInteger
(NSMutableData initWithCapacity:
的参数1}})。结果是-1(内部表示为0xffffffff)最终为4294967295(内部也表示为0xffffffff)。
在这种情况下,您必须测试NSURLResponseUnknownLength
并使用不同的初始容量。并且不要使用NSNumber
。如果签名long long
在合理范围内,只需将其转换为无符号NSUInteger
。