我想确定正在下载的文件的fileSize。 我使用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告诉我文件路径是正确的。但为什么它在下载时告诉我该文件不存在?我该如何解决这个问题?
答案 0 :(得分:0)
使用ASIHTTP lib进行网络,您可以轻松完成。
阅读“自定义进度跟踪”部分。
或者您可以使用
-(NSURLRequest *)connection:(NSURLConnection *)connection
willSendRequest:(NSURLRequest *)request
redirectResponse:(NSURLResponse *)response {
}
long long size = [response expectedContentLength];
但是在这样的网站上有很多解决方案:
http://goo.gl/0hrK2
答案 1 :(得分: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。
答案 2 :(得分: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]);
}
}