Fork me on https://github.com

SDWebImage, 关于第三方异步加载图片的一些方法

SDWebImage, 关于第三方异步加载图片的一些方法

1.首先将第三方文件(SDWebImage)添加到工程里

2.修改ARC

           

3.在viewControl中添加一个imageView, 添加一个tap点击手势, 用来展示下载的图片

a.  sd_setImageWithURL

引入头文件

 #import "UIImageView+WebCache.h" 

- (IBAction)tap:(UITapGestureRecognizer *)sender {
    NSLog(@"%s", __FUNCTION__);
    //异步加载图片
    [self.imageView sd_setImageWithURL:[NSURL URLWithString:@"http://img3.douban.com/view/photo/photo/public/p1910869260.jpg"] placeholderImage:nil options:0];
}

b. SDWebImageManager

引入头文件

 #import "SDWebImageManager.h" 

- (IBAction)tap:(UITapGestureRecognizer *)sender {
    NSLog(@"%s", __FUNCTION__);
    //异步加载图片
    SDWebImageManager *manager = [SDWebImageManager sharedManager];
    [manager downloadImageWithURL:[NSURL URLWithString:@"http://img3.douban.com/view/photo/photo/public/p2151245053.jpg"] options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) {
        
    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
        if (finished) {
            self.imageView.image = image;
        }
    }];
}

c. SDWebImageDownloader 独立使用异步图片下载

引入头文件

 #import "SDWebImageDownloader.h" 

    SDWebImageDownloader *downloader = [SDWebImageDownloader sharedDownloader];
    [downloader downloadImageWithURL:[NSURL URLWithString:@"http://img4.douban.com/view/photo/photo/public/p1940511226.jpg"] options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) {
      
    } completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
        if (finished) {
            self.imageView.image = image;
        }
    }];

d. SDImageCache 

缓存图片key值来标记图片提取图片下次要使用时能快速提取使用图片

引入头文件

 #import "UIImageView+WebCache.h" 

- (IBAction)tap:(UITapGestureRecognizer *)sender {
    NSLog(@"%s", __FUNCTION__);
    //SDImageCache单例方法
    [[SDImageCache sharedImageCache] storeImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://img3.doubanio.com/view/photo/photo/public/p522751329.jpg"]]] forKey:@"mySpace"];
    //queryDiskCacheForKey, 通过key值, 查找缓存的图片
    [[SDImageCache sharedImageCache] queryDiskCacheForKey:@"mySpace" done:^(UIImage *image, SDImageCacheType cacheType) {
                self.imageView.image = image;
    }];
}
再次使用图片时不需要再下载, 直接从缓存里提取
- (IBAction)other:(UITapGestureRecognizer *)sender {
    NSLog(@"other");
    [[SDImageCache sharedImageCache] queryDiskCacheForKey:@"mySpace" done:^(UIImage *image, SDImageCacheType cacheType) {
        self.otherImage.image = image;
    }];
}

点击imageView将图片缓存用"mySpace"标志缓存, 并将其显示出来, 再点击另一个view将这张图片用"mySpace"标志从缓存中提取出来, 不用重新下载, 能快速的展现出来

               

posted @ 2015-11-14 17:37  OrangesChen  阅读(319)  评论(0编辑  收藏  举报