1

我想确定正在下载的文件的文件大小。我使用 ASIHTTPRequest 并且通常它应该跳转到 didReceiveBytes 但它没有这样做相反我启动了一个计时器来重复检查该位置的文件大小。像这样 :

NSError* error;
NSFileManager* fm = [NSFileManager defaultManager];
NSDictionary* itemAttributes = [fm attributesOfItemAtPath:_location error:&error];
if(!error){
    unsigned long long fsize = [itemAttributes fileSize];
    [downloadLabel setText:[NSString stringWithFormat:@"%llu MB downloaded",fsize] ];
    NSLog(@"MB downloaded: %llu", fsize);
} else {
    NSLog(@"error=%@", error);
}

问题是,在文件完成下载之前,我收到以下错误:

  error=Error Domain=NSCocoaErrorDomain Code=260 "The operation couldn’t be completed.             (Cocoa error 260.)" UserInfo=0xf57aa60 {NSFilePath= "long filename", NSUnderlyingError=0xf57ad90 "The operation couldn’t be completed. No such file or directory"

完成后它终于给了我:

MB下载:34443951

事实上,我最后下载的 MB 告诉我文件路径是正确的。但是为什么它在下载时告诉我该文件不存在?我该如何解决?

4

3 回答 3

0

最后,我最终直接从 ASIHTTP 请求中请求字节:

unsigned long long bytes = request.totalBytesRead;
double mb;
if(bytes >0){
    mb = bytes/1000000.0f;        
    [downloadLabel setText:[NSString stringWithFormat:@"%.2f MB downloaded",mb] ];
}

使用触发的计时器不断检索此值以更新下载的字节并转换为表示 MB。

于 2012-08-09T16:04:30.153 回答
0

使用网络的ASIHTTP库,你可以很容易地做到这一点。

阅读“自定义进度跟踪”部分。

或者你可以使用

-(NSURLRequest *)connection:(NSURLConnection *)connection
        willSendRequest:(NSURLRequest *)request
       redirectResponse:(NSURLResponse *)response {
}

long long size = [response expectedContentLength];

但是so站点中有很多解决方案:http:
//goo.gl/0hrK2

于 2012-08-01T09:35:10.933 回答
0

试试这个代码,它可以帮助你

- (void)request:(ASIHTTPRequest *)request didReceiveData:(NSData *)data
{

    [request contentLength];
    [downloadButtton setTitle:@"Cancel" forState:UIControlStateNormal];
    [downloadButtton addTarget:self action:@selector(cancelDownloading) forControlEvents:UIControlEventTouchUpInside];
    long length = [request contentLength];

    fileLength = length;

    NSLog(@"fileLength ====> %f",fileLength);


  //  progressView.hidden=NO;
   // progressText.hidden=NO;
    double length2 = [data length];
    currentLength += length2;
    //    double progress = currentLength/fileLength;



  NSString *firstDataLength=[NSString stringWithFormat:@"%.2f MB",fileLength/1024/1024 ];
   NSString *totalMBytes=[NSString stringWithFormat:@" of %.2f MB",fileLength/1024/1024 ];
   NSString *totalMBytesWritten=[NSString stringWithFormat:@"%.2f MB",currentLength/1024/1024];


    NSLog(@"firstDataLength %@",firstDataLength);
    NSLog(@"totalMBytes %@",totalMBytes);
    NSLog(@"totalMBytesWritten %@",totalMBytesWritten);



    progressText.text=[totalMBytesWritten stringByAppendingString:totalMBytes];
    NSUInteger left = [data length];
    NSUInteger nwr = 0;
    do {
        nwr = [fileStreem write:[data bytes] maxLength:left];
        if (-1 == nwr) break;
        left -= nwr;
    } while (left > 0);
    if (left) {
        NSLog(@"stream error: %@", [fileStreem streamError]);
    }


}
于 2013-02-06T06:18:06.007 回答