iphone - 异步图像下载器

标签 iphone image user-interface asynchronous download

我编写了一个小类来使用 NSURLConnection 执行图像下载。 其想法是将下载委托(delegate)给此类以避免阻止执行。

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

-(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:

- (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,知道吗? (实际上,当我点击它时,单元格会更新) 有更好的方法来实现这个功能吗? (实际上需要的是:非阻塞、缓存系统)

最佳答案

塞萨尔

对于异步图像加载、缓存和线程操作,我使用 http://github.com/rs/SDWebImage 中的 SDImageCache 类。我也自己写过好几次,但是这个非常棒,而且我已经扔掉了所有旧代码。

来自其文档:

Just #import the UIImageView+WebCache.h header, and call the setImageWithURL:placeholderImage: method from the tableView:cellForRowAtIndexPath: UITableViewDataSource method. Everything will be handled for you, from async downloads to caching management.

希尔顿

关于iphone - 异步图像下载器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4038726/

相关文章:

iphone - 在应用内征求评论

iphone - 如何在不检查操作系统版本的情况下检测 iOS 上的 YouTube 应用程序(或缺少该应用程序)?

Javascript 在旧浏览器中执行点击 html "image"

java - Swing GUI 与域逻辑通信的最佳方式?

java - GUI 上的滚动条

iphone - CALayer -drawInContext : and -renderInContext:? 之间有什么区别

iphone - 在 Xcode 中,当切换构建配置时链接的静态库变红是什么意思?

Java图像显示

jquery检查img是否有src

javafx - KeyEvent.getCharacter() 返回以 null 结尾的字符