获取大小文件NSURLConnection? [英] get size file NSURLConnection?

查看:103
本文介绍了获取大小文件NSURLConnection?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

错误如下:
[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;
}


推荐答案

expectedContentLength 不是未签名的值。其类型为 long long ,它是带符号的。

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

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.

分配NSData对象时检查 NSURLResponseUnknownLength

Check for NSURLResponseUnknownLength when allocating your NSData object.

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

当然,如果您不知道内容大小,可以t显示进度条。在这种情况下,您应该显示其他进度指示器。

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 ;-)

此代码也是错误的:

[data2 appendData:recievedData];

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

首先将数据追加到data2,然后检查data2是否为nil 。如果为零,则将其丢掉。您应该先检查零。或者只是在 connection:didReceiveResponse:

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:

这篇关于获取大小文件NSURLConnection?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆