`
v5browser
  • 浏览: 1137189 次
社区版块
存档分类
最新评论

iOS学习笔记46——图片异步加载之SDWebImage

阅读更多

在开发中经常会遇到列表加载的功能,其中大部分都包括图片列表加载,但移动设备本身内存有限,而大量图片加载又很耗内存。今天主要就介绍一个第三方图片异步加载库SDWebImage,Github地址为:https://github.com/rs/SDWebImage,这个库主要实现了为UIImageView添加一个类别方法,让使用者使用图片异步加载就好像直接为UIImageView设置image一样,使用非常方便。

一、主要功能

  • An UIImageView category adding web image and cache management to the Cocoa Touch framework
  • An asynchronous image downloader
  • An asynchronous memory + disk image caching with automatic cache expiration handling
  • Animated GIF support
  • WebP format support
  • A background image decompression
  • A guarantee that the same URL won't be downloaded several times
  • A guarantee that bogus URLs won't be retried again and again
  • A guarantee that main thread will never be blocked
  • Performances!
  • Use GCD and ARC
包括图片异步下载器、内存和本地缓存、GIF支持、相同URL不会重复下载、不会阻塞UI线程等。


二、集成使用步骤

  • Download and unzip the last version of the framework from thedownload page(下载framwork包并解压)
  • Right-click on the project navigator and select "Add Files to "Your Project":(右击工程选择添加库到项目工程)
  • In the dialog, select SDWebImage.framework:(选择SDWebImage.framwork库)
  • Check the "Copy items into destination group's folder (if needed)" checkbox(选择拷贝到工程复选框)
  • 添加ImageIO.framework库支持
  • 添加Linker Flag,如下图


按下Command+B,编译工程,如果编译成功则说明集成成功了,如果出现framwork找不到的异常,则将工程目录中SDWebImage-3.3.framwork改名为SDWebImage.framwork再编译就没问题了,由于我下的是最新3.3版本,可能原配置文件搜索的编译路径名是不带“-3.3”的,所以提一下这个问题。配置和编译成功后就可以开始使用了:

三、Demo实现
先看看最终实现的效果图,主要实现了UITableView的列表加载和单个图片的异步加载:


在需要使用异步图片加载的头文件导入:

#import <SDWebImage/UIImageView+WebCache.h>

列表实现在UITableView的协议方法中只需要很简单的调用UIImageView的类别方法即可完成异步加载:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *Identifier = @"UITableViewIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:Identifier];
    }

    NSInteger row = indexPath.row;
    cell.textLabel.text = @"My Text";
    [cell.imageView setImageWithURL:[arr_imgs objectAtIndex:row]];
    
    return cell;
}

单击UITableView的item进入单个图片加载页面,使用SDWebImageDownloader加载:

//单独异步下载一个图片
    [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:[NSURL URLWithString:self.imgURL] options:0 progress:^(NSUInteger receivedSize, long long expectedSize) {
        
    } completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
        if (image && finished) {
            imageView.image = image;
        }
    }];

以上只给出关键代码,具体Demo详情请下载工程源码:下载


加入我们的或微信公众账号请查看:Ryan's zone公众账号及

同时欢迎关注我的新浪微博和我交流:@唐韧_Ryan


觉得这篇文章对你有用就顶我一下吧!偷笑

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics