在iphone中下载图像时,在UIProgressView中显示准确的进度 [英] Showing Accurate Progress In UIProgressView While Downloading Images in iphone

查看:92
本文介绍了在iphone中下载图像时,在UIProgressView中显示准确的进度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有四个包含图片的网址...
我正在将这些图片下载并将它们放入文档文件夹..



这是我的代码..

   - (void)viewDidLoad 
{
NSMutableArray * myUrlsArray = [[NSMutableArray alloc] init];
[myUrlsArray addObject:@http://blogs.sfweekly.com/thesnitch/steve_jobs3.jpg];
[myUrlsArray addObject:@http://www.droid-life.com/wp-content/uploads/2012/12/Steve-Jobs-Apple.jpg];
[myUrlsArray addObject:@http://2.bp.blogspot.com/-T6nbl0rQoME/To0X5FccuCI/AAAAAAAAEZQ/ipUU7JfEzTs/s1600/steve-jobs-in-time-magazine-front-cover.png] ;
[myUrlsArray addObject:@http://images.businessweek.com/ss/08/09/0929_most_influential/image/steve_jobs.jpg];
[myUrlsArray addObject:@http://cdn.ndtv.com/tech/gadget/image/steve-jobs-face.jpg];

for(int i = 0; i< myUrlsArray.count; i ++)
{
[self downloadImageFromURL:[myUrlsArray objectAtIndex:i] withName:[NSString stringWithFormat:@ MYIMAGE%i.jpeg,I]];
}

}




#pragma mark-下载文件

- ( void)downloadImageFromURL:(NSString *)myURLString withName:(NSString *)fileName
{
UIImage * image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:myURLString]]];

NSLog(@%f,%f,image.size.width,image.size.height);

//让我们将文件保存到Document文件夹中。**

NSString * documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)objectAtIndex:0];

NSString * jpegPath = [NSString stringWithFormat:@%@ /%@,documentsPath,fileName]; //此路径如果要在sqlite中保存引用路径
NSData * data2 = [NSData dataWithData:UIImageJPEGRepresentation(image,1.0f)]; // 1.0f = 100%quality
[data2 writeToFile:jpegPath atomically:YES];

}

现在......我需要显示一个UIProgressView可以准确地上传下载进度。



如何实现此功能...



任何人都可以提供一些指导来实现这一目标..



提前致谢...

解决方案

我建议您使用一些异步下载技术(AFNetworking,SDWebImage,或者使用委托自己动手)基于 NSURLSession )而不是 dataWithContentsOfURL 以便(a)你不阻止主队列; (b)随着下载的进行,您可以获得进度更新。



我还建议创建 NSProgress 。当您的委托方法获取有关已下载的字节数的更新时,请更新 NSProgress 对象。



然后您可以将每个 NSProgress observeProgress UIProgressView ,当您更新 NSProgress 时,UI可以自动更新。



或者,如果您和单个 UIProgressView 显示所有 NSProgress的总进度每次下载,你可以创建一个父 NSProgress ,建立每个下载的 NSProgress 作为父的子女 NSProgress ,然后,当每次下载更新其各自的 NSProgress 时,这将自动生成触发父 NSProgress 的计算。再次,您可以将该父 NSProgress 绑定到主 UIProgressView ,然后您将自动更新UI总进度,只需让每次下载更新个人 NSProgress






<但是,有一个技巧,因为有些Web服务不会通知您预期的字节数。他们将报告 NSURLResponseUnknownLength 的预期字节数,即-1! (有合理的理由说明为什么它可能超出了这个问题的范围。)这显然使得很难计算下载的百分比。



例子,有几种方法:


  1. 你可以举手并只使用不确定的进度指示器;


  2. 您可以尝试更改请求,以便Web服务报告有意义的预期字节数值(例如 https://stackoverflow.com/a/22352294/1271826 );或


  3. 您可以使用估计下载大小来估算完成百分比。例如,如果您知道您的图片平均每个100kb,您可以执行以下操作来更新与特定下载相关联的 NSProgress

      if(totalBytesExpectedToWrite> = totalBytesWritten){
    self.progress.totalUnitCount = totalBytesExpectedToWrite;
    } else {
    if(totalBytesWritten< = 0){
    self.progress.totalUnitCount = kDefaultImageSize;
    } else {
    double written =(double)totalBytesWritten;
    double percent = tanh(write /(double)kDefaultImageSize);
    self.progress.totalUnitCount = written / percent;
    }
    }

    self.progress.completedUnitCount = totalBytesWritten;

    这是一个使用 tanh 函数返回完成百分比值,该值平滑且渐近逼近100%,使用 kDefaultImageSize 作为估算的基础。



    这并不完美,但它可以为完成百分比提供相当不错的代理。



I have four urls which consists images... I'm downloding those images and placing them into documents folder..

here is my code..

-(void)viewDidLoad
{
NSMutableArray *myUrlsArray=[[NSMutableArray alloc]init];
[myUrlsArray addObject:@"http://blogs.sfweekly.com/thesnitch/steve_jobs3.jpg"];
[myUrlsArray addObject:@"http://www.droid-life.com/wp-content/uploads/2012/12/Steve-Jobs-Apple.jpg"];
[myUrlsArray addObject:@"http://2.bp.blogspot.com/-T6nbl0rQoME/To0X5FccuCI/AAAAAAAAEZQ/ipUU7JfEzTs/s1600/steve-jobs-in-time-magazine-front-cover.png"];
[myUrlsArray addObject:@"http://images.businessweek.com/ss/08/09/0929_most_influential/image/steve_jobs.jpg"];
[myUrlsArray addObject:@"http://cdn.ndtv.com/tech/gadget/image/steve-jobs-face.jpg"];

for (int i=0; i<myUrlsArray.count; i++)
{
    [self downloadImageFromURL:[myUrlsArray objectAtIndex:i] withName:[NSString stringWithFormat:@"MyImage%i.jpeg",i]];
}

}




#pragma mark- downloading File

-(void)downloadImageFromURL:(NSString *)myURLString withName:(NSString *)fileName
{
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:myURLString]]];

NSLog(@"%f,%f",image.size.width,image.size.height);

   // Let's save the file into Document folder.**

    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0];

NSString *jpegPath = [NSString stringWithFormat:@"%@/%@",documentsPath,fileName];// this path if you want save reference path in sqlite
NSData *data2 = [NSData dataWithData:UIImageJPEGRepresentation(image, 1.0f)];//1.0f = 100% quality
[data2 writeToFile:jpegPath atomically:YES];

}

NOW... I need to display a UIProgressView for above downloading progress accurately.

how can i achieve this functionality...

Can any one provide some guidelines to achieve this..

Thanks in advance...

解决方案

I'd suggest you use some asynchronous downloading technique (either AFNetworking, SDWebImage, or roll your own with delegate-based NSURLSession) rather than dataWithContentsOfURL so that (a) you don't block the main queue; and (b) you can get progress updates as the downloads proceed.

I'd also suggest creating a NSProgress for each download. When your delegate method gets updates about how many bytes have been downloaded, update the NSProgress object.

You then can associate each NSProgress with a observedProgress for a UIProgressView, and when you update your NSProgress, the UI can be updated automatically.

Or, if you and a single UIProgressView to show the aggregate progress of all of the NSProgress for each download, you can create a parent NSProgress, establish each download's NSProgress as a child of the parent NSProgress, and then, as each download updates its respective NSProgress, this will automatically trigger the calculation of the parent NSProgress. And again, you can tie that parent NSProgress to a master UIProgressView, and you'll automatically update the UI with the total progress, just by having each download update its individual NSProgress.


There is a trick, though, insofar as some web services will not inform you of the number of bytes to be expected. They'll report an "expected number of bytes" of NSURLResponseUnknownLength, i.e. -1! (There are logical reasons why it does that which are probably beyond the scope of this question.) That obviously makes it hard to calculate what percentage has been downloaded.

In that case, there are a few approaches:

  1. You can throw up your hands and just use an indeterminate progress indicator;

  2. You can try changing the request such that web service will report meaningful "expected number of bytes" values (e.g. https://stackoverflow.com/a/22352294/1271826); or

  3. You can use an "estimated download size" to estimate the percentage completion. For example, if you know your images are, on average, 100kb each, you can do something like the following to update the NSProgress associated with a particular download:

    if (totalBytesExpectedToWrite >= totalBytesWritten) {
        self.progress.totalUnitCount = totalBytesExpectedToWrite;
    } else {
        if (totalBytesWritten <= 0) {
            self.progress.totalUnitCount = kDefaultImageSize;
        } else {
            double written = (double)totalBytesWritten;
            double percent = tanh(written / (double)kDefaultImageSize);
            self.progress.totalUnitCount = written / percent;
        }
    }
    
    self.progress.completedUnitCount = totalBytesWritten;
    

    This is a bit of sleight of hand that uses the tanh function to return a "percent complete" value that smoothly and asymptotically approaches 100%, using the kDefaultImageSize as the basis for the estimation.

    It's not perfect, but it yields a pretty decent proxy for percent completion.

这篇关于在iphone中下载图像时,在UIProgressView中显示准确的进度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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