我有一个从服务器下载图片的应用程序。我想向用户展示一下进展情况。我在苹果的文档上读过关于UIProgressView的文章,在这个网站上读过很多答案,但我无法让它发挥作用。这是我的viewDidLoad中的代码
_profileProgressView.hidden= YES;
_profileProgressView.progress = 0.0;在我的- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response中,我显示了UIProgressView,然后得到了图像的预期大小。
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
self.profileProgressView.hidden= NO;
[self.remote_response setLength:0];
received = 0;
self.filesize = [NSNumber numberWithLongLong:[response expectedContentLength]];
NSLog(@"Content Length::%@", self.filesize);
}在我的- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)d中,我计算下载图像的百分比,然后更新UIProgressView的进度并记录下载进度。
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)d {
[self.remote_response appendData:d];
NSNumber *resourceLength = [NSNumber numberWithUnsignedInteger:[self.remote_response length]];
dispatch_async( dispatch_get_main_queue(), ^ {
float progress = (_profileProgressView.progress + ([self.filesize floatValue]/[resourceLength floatValue])*100);
[self.profileProgressView setProgress:progress animated:YES];
NSLog(@"Downloading %.0f%% complete", _profileProgressView.progress);
});
}当我运行这段代码时
Downloading 0% complete。我希望得到正在下载的图像的日志。此外,我认为我应该在alloc和init的UIProgressView在viewDidDownload,当我这样做,我得到UIProgressView,但它没有显示的进展,并没有隐藏完成后,图像被下载。
发布于 2013-08-27 04:17:50
我认为,您已经过度复杂化了装箱的数学问题,并用NSNumber取消了数据类型的装箱。
我要做的是创建三个变量:
double fileLength;
double lastProgress;
double currentLength;然后做简单的数学:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
fileLength = [response expectedContentLength];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)d {
double length = [d length];
currentLength += length;
double progress = currentLength/fileLength;
if (lastProgress < progress) {
profileProgressView.progress = progress;
lastProgress = progress;
}
}发布于 2013-08-27 06:06:00
我以前也经历过同样的问题。在这种情况下,我们无法显示精确的进度视图。为了显示精确的进度,您的服务器应该提供在响应头中发送的字节。然后oly,您就可以在连接中获得确切的数据:didReceiveData:委托。否则,你马上就会得到1.0。
即使您想在这种情况下显示进度视图而不依赖服务器,也可以通过将数据的长度分成n个步骤来实现,并使用NSTimer对其进行改进。
https://stackoverflow.com/questions/18456689
复制相似问题