首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >异步镜像下载器

异步镜像下载器
EN

Stack Overflow用户
提问于 2010-10-28 08:08:56
回答 5查看 3.9K关注 0票数 2

我已经编写了一个小类来使用NSURLConnection执行图像下载。它的想法是将下载委托给这个类,以避免阻塞执行。

因此,我将目标UIImageView (通过ref)和url传递给函数并开始下载:

代码语言:javascript
复制
-(void)getImage:(UIImageView**)image formUrl:(NSString*)urlStr
{
    NSLog(@"Downloader.getImage.url.debug: %@",urlStr);
    NSURL *url = [NSURL URLWithString:urlStr];
    NSURLRequest *req = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:5.0];
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    NSURLConnection *c = [[NSURLConnection alloc] initWithRequest:req delegate:self];
    [conn addObject:c];
    int i = [conn indexOfObject:c];
    [imgs insertObject:*image atIndex:i];
    [c release];
}

完成后,设置图像并更新imageView:

代码语言:javascript
复制
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    int i = [conn indexOfObject:connection];

    NSData *rawData = [buffer objectAtIndex:i];
    UIImage *img = [UIImage imageWithData:rawData];
    UIImageView *imgView = [imgs objectAtIndex:i];
    imgView.image = img;

    [imgView setNeedsDisplay];

    [conn removeObjectAtIndex:i];
    [imgs removeObjectAtIndex:i];
    [buffer removeObjectAtIndex:i];

    if ([conn count]==0) {
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    }
}

这个系统运行得很好,但是我无法更新UITableViewCell单元中的UIImageView,你有什么想法吗?(实际上,当我点击它时它会更新的单元格)有更好的方法来实现这个功能吗?(实际上需要的是:非阻塞、缓存系统)

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2010-10-28 10:05:41

塞萨尔

对于异步图像加载、缓存和线程化操作,我使用http://github.com/rs/SDWebImage中的SDImageCache类。我也写了几次自己的代码,但这一次很棒,我把所有的旧代码都扔掉了。

从它的文档中:

只需#import UIImageView+WebCache.h头,并从tableView:cellForRowAtIndexPath: UITableViewDataSource方法调用setImageWithURL:placeholderImage:方法。一切都将为您处理,从异步下载到缓存管理。

希尔顿

票数 6
EN

Stack Overflow用户

发布于 2012-10-18 20:20:20

只需执行以下步骤:

代码语言:javascript
复制
    1) Download SDWebImage below  And drag to your xcode project. 

Click here to Download the SDWebImage

代码语言:javascript
复制
   2) Write the following code in your .h file #import "UIImageView+WebCache.h"
   3) Write the following code for your image view 
  [yourImageView setImageWithURL:[NSURL URLWithString:@"www.sample.com/image.png"]];

这就是它的..。你已经做到了!

票数 3
EN

Stack Overflow用户

发布于 2011-11-28 21:14:43

代码语言:javascript
复制
NSAutoreleasePool *pool=[[NSAutoreleasePool alloc]init];
    [img_data setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:self.str_url]]]];
    [pool release];
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4038726

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档