iOS网络加载图片缓存策略之ASIDownloadCache缓存优化
在我们实际工程中,很多情况需要从网络上加载图片,然后将图片在imageview中显示出来,但每次都要从网络上请求,会严重影响用户体验,为了不是每次显示都需要从网上下载数据,希望将图片放到本地缓存,因此我们需要一个好的的缓存策略,今天我将我在项目工程中的实际经验分享给大家,我这里主要介绍一下强大的ASIHTTPRequest的缓存策略,以及使用方法。
AD:
在我们实际工程中,很多情况需要从网络上加载图片,然后将图片在imageview中显示出来,但每次都要从网络上请求,会严重影响用户体验,为了不是每次显示都需要从网上下载数据,希望将图片放到本地缓存,因此我们需要一个好的的缓存策略,今天我将我在项目工程中的实际经验分享给大家,我这里主要介绍一下强大的ASIHTTPRequest的缓存策略,以及使用方法:
下面是具体步骤:
一、设置缓存策略
首先在SplitDemoAppDelegate委托代理中,实现如下代码:
在SplitDemoAppDelegate.h文件中,代码如下:
- #import <UIKit/UIKit.h>
- @class ASIDownloadCache;
- @interface SplitDemoAppDelegate : NSObject <UIApplicationDelegate,UITabBarControllerDelegate> {
- UIWindow *_window;
- ASIDownloadCache*_downloadCache; //下载缓存策略
- }
- @property (nonatomic, retain) ASIDownloadCache*downloadCache;
- @end
在SplitDemoAppDelegate.m文件中,代码如下:
- #import "SplitDemoAppDelegate.h"
- @implementation SplitDemoAppDelegate
- @synthesize window=_window;
- @synthesize downloadCache = _downloadCache;
- - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
- {
- //初始化ASIDownloadCache缓存对象
- ASIDownloadCache *cache = [[ASIDownloadCache alloc] init];
- self.downloadCache = cache;
- [cache release];
- //路径
- NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
- NSString *documentDirectory = [paths objectAtIndex:0];
- //设置缓存存放路径
- [self.downloadCache setStoragePath:[documentDirectorystringByAppendingPathComponent:@"resource"]];
- //设置缓存策略
- [self.downloadCache setDefaultCachePolicy:ASIOnlyLoadIfNotCachedCachePolicy];
- // Override point for customization after application launch.
- [self.window makeKeyAndVisible];
- return YES;
- }
- - (void)dealloc
- {
- [_window release];
- [_downloadCache release];
- [super dealloc];
- }
- @end
二、创建缓存线程
这一步是创建一个NSOperation类,实现缓存的方法,代码如下:
ResourceContainer.h文件实现:
- #import <Foundation/Foundation.h>
- #import "ASIHTTPRequest.h"
- #import "SplitDemoAppDelegate.h"
- @interface ResourceContainer : NSOperation {
- NSURL*_resourceURL; //资源请求url
- NSObject*_hostObject;
- SEL_resourceDidReceive; //资源接手响应方法
- SplitDemoAppDelegate*_appDelegate; //应用委托对象
- ASIHTTPRequest*_httpRequest;
- UIImageView*_imageView;
- }
- @property (nonatomic, retain) NSURL*resourceURL;
- @property (nonatomic, retain) NSObject*hostObject;
- @property (nonatomic, assign) SELresourceDidReceive;
- @property (nonatomic, assign) SplitDemoAppDelegate *appDelegate;
- @property (nonatomic, retain) ASIHTTPRequest*httpRequest;
- @property (nonatomic, retain) UIImageView*imageView;
- //http请求回调方法
- -(void)didStartHttpRequest:(ASIHTTPRequest *)request;
- -(void)didFinishHttpRequest:(ASIHTTPRequest *)request;
- -(void)didFailedHttpRequest:(ASIHTTPRequest *)request;
- //取消资源请求
- -(void)cancelReourceGet;
- //资源接收回调方法
- -(void)resourceDidReceive:(NSData *)resource;
- @end
ResourceContainer.m文件实现:
- #import "ResourceContainer.h"
- #import "HttpConstant.h"
- #import "ASIDownloadCache.h"
- @implementation ResourceContainer
- @synthesize resourceURL = _resourceURL;
- @synthesize hostObject = _hostObject;
- @synthesize resourceDidReceive = _resourceDidReceive;
- @synthesize appDelegate = _appDelegate;
- @synthesize httpRequest = _httpRequest;
- @synthesize imageView = _imageView;
- -(id)init{
- if(self == [super init]){
- self.appDelegate = (SplitDemoAppDelegate *)[[UIApplication sharedApplication] delegate];
- }
- return self;
- }
- -(void)main{
- if(self.hostObject == nil)
- return;
- if(self.resourceURL == nil){
- [self resourceDidReceive:nil];
- return;
- }
- ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:self.resourceURL]
- self.httpRequest = request;
- [self.httpRequest setDownloadCache:self.appDelegate.downloadCache];
- [self.httpRequest setDelegate:self];
- [self.httpRequest setDidStartSelector:@selector(didStartHttpRequest:)];
- [self.httpRequest setDidFinishSelector:@selector(didFinishHttpRequest:)];
- [self.httpRequest setDidFailSelector:@selector(didFailedHttpRequest:)];
- //发异步请求
- [self.httpRequest startAsynchronous];
- }
- - (void)dealloc {
- [_resourceURL release];
- [_hostObject release];
- [_httpRequest release];
- [_imageView release];
- [super dealloc];
- }
- //开始请求
- -(void)didStartHttpRequest:(ASIHTTPRequest *)request{
- [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
- }
- //请求成功返回处理结果
- -(void)didFinishHttpRequest:(ASIHTTPRequest *)request{
- [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
- if([request responseStatusCode] == 200 || [request responseStatusCode] == 304){
- //判断是否来自缓存
- if([request didUseCachedResponse]){
- NSLog(@"=========资源请求:%@ 来自缓存============",[self.resourceURL absoluteURL]);
- }
- else{
- NSLog(@"=========资源请求:图片不来自缓存============");
- }
- [self resourceDidReceive:[request responseData]];
- }
- else {
- [self resourceDidReceive:nil];
- }
- }
- //失败请求返回处理结果
- -(void)didFailedHttpRequest:(ASIHTTPRequest *)request{
- [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
- [self resourceDidReceive:nil];
- }
- //取消资源请求
- -(void)cancelReourceGet{
- [self.httpRequest cancel];
- }
- //资源接收处理方法
- -(void)resourceDidReceive:(NSData *)resource{
- if([self.hostObject respondsToSelector:self.resourceDidReceive]){
- if(resource != nil && self.imageView != nil){
- self.imageView.image = [UIImage imageWithData:resource];
- }
- [self.hostObject performSelectorOnMainThread:self.resourceDidReceive withObject:self.imageViewwaitUntilDone:NO];
- }
- }
- @end
到第二步,我们的缓存策略的设置,以及资源请求和接收数据方法已经构建完毕,下面介绍一下如何使用我们上面创建的NSOperation类
三、图片请求(利用上面创建的类)
这里以我的工程为例进行分析:
在DetailViewController.h声明文件中:
- #import <UIKit/UIKit.h>
- @interface DetailViewController :UIViewController {
- NSURL *_imageURL; //图片url
- NSMutableArray *_originalIndexArray; //保存请求图片的号
- NSMutableDictionary *_originalOperationDic; //保存图片请求队列
- NSOperationQueue *_requestImageQueue; //图片请求队列
- }
- @property (nonatomic, retain) NSURL *imageURL;
- @property (nonatomic, retain) NSMutableArray *originalIndexArray;
- @property (nonatomic, retain) NSMutableDictionary *originalOperationDic;
- @property (nonatomic, retain) NSOperationQueue * requestImageQueue;
- //显示图片信息
- -(void)displayProductImage;
- //根据图片序号显示请求图片资源
- -(void)displayImageByIndex:(NSInteger)index ByImageURL:(NSURL *)url;
- //处理图片请求返回信息
- -(void)imageDidReceive:(UIImageView *)imageView;
- @end
在DetailViewController.m实现文件中:
- #import "ProductDetailViewController.h"
- //这里引入在第二步中,我们创建的对象
- #import "ResourceContainer.h"
- @implementation DetailViewController
- @synthesize imageURL = _imageURL;
- @synthesize originalIndexArray = _originalIndexArray;
- @synthesize originalOperationDic = _originalOperationDic;
- @synthesize requestImageQueue = _requestImageQueue;
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- NSOperationQueue *tempQueue = [[NSOperationQueue alloc] init];
- self.requsetImageQueue = tempQueue;
- [tempQueue release];
- NSMutableArray *array = [[NSMutableArray alloc] init];
- self.originalIndexArray = array;
- [array release];
- NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
- self.originalOperationDic = dic;
- [dic release];
- }
- //显示图片信息
- -(void)displayProductImage
- {
- NSURL *url = [NSURL URLWithString:@"http://xxx.xxx.xxx.xxx"];
- //这个是从器返回有图片数目,self.xxxx根据具体的场合
- int imageCount = [self.xxxx.imageNum intValue];
- for (int i=0; i<imageCount; i++) {
- NSString *str1 = @"这里是拼图片请求url,根据实际需求";
- self.imageURL = [url URLByAppendingPathComponent:str1];
- //根据图片号请求资源
- [self displayImageByIndex:i ByImageURL:self.productImageURL];
- }
- }
- //根据图片序号显示请求图片资源
- -(void) displayImageByIndex:(NSInteger)index ByImageURL:(NSURL *)url
- {
- NSString *indexForString = [NSString stringWithFormat:@"%d",index];
- //若数组中已经存在该图片编号,说明图片加载完毕,直接返回
- if ([self.originalIndexArray containsObject:indexForString]) {
- return;
- }
- //创建UIImageView对象
- UIImageView *imageView = [[UIImageView alloc] init];
- imageView.tag = index;
- //创建资源请求对象
- ResourceContainer *imageOperation = [[ResourceContainer alloc] init];
- imageOperation.resourceURL = url;
- imageOperation.hostObject = self;
- //设置收到图片信息处理理方法
- imageOperation.resourceDidReceive = @selector(imageDidReceive:);
- imageOperation.imageView = imageView;
- [imageView release];
- //将图片请求对象加入图片请求队列中
- [self.requsetImageQueue addOperation:imageOperation];
- [self.originalOperationDic setObject:imageOperation forKey:indexForString];
- [imageOperation release];
- }
- //处理图片请求返回信息
- -(void)imageDidReceive:(UIImageView *)imageView
- {
- if (imageView == nil||imageView.image == nil) {
- imageView.image = [UIImage imageNamed:@"no-pic-300-250.png"];
- }
- //将图片信息加载到前台,self.openFlowView是我用的coverFlow,coverFlow的使用方法网上很多,自己找吧
- [self.openFlowView setImage:imageView.image forIndex:imageView.tag];
- [self.originalIndexArray addObject:[NSString stringWithFormat:@"%d",imageView.tag]];
- [self.originalOperationDic removeObjectForKey:[NSString stringWithFormat:@"%d",imageView.tag]];
- }
- - (void)dealloc
- {
- [_requestImageQueue release];
- [_originalIndexArray release];
- [_originalOperationDic release];
- [_imageURL release];
- [super dealloc];
- }
- @end
经过上述步骤,我们实现了加载网络图片时缓存功能,增强了用户体验效果。代码中可能会有诸多问题,希望网友指教,有更好的缓存方法,也希望一起交流!
经验总结。本书共17章,
转载于:https://www.cnblogs.com/OIMM/p/4941507.html
iOS网络加载图片缓存策略之ASIDownloadCache缓存优化相关推荐
- Android:ViewPager详解(异步网络加载图片,带图片缓存,并带导航小圆点)
android 应用中,如欢迎指引页面, 和图片轮播功能, 或者更多的内容在一页显示不了,要分成多个页面,这时候viewpager是很好用的. 首先看下效果: 下面是一个例子,带异步网络加载图片,并带 ...
- Flutter Image从网络加载图片刷新、强制重新渲染
Flutter自带的Image.network()从网络加载图片后,如果服务器上的图片改变了,但是url没变,就算使用setState进行rebuild,图片也不会跟着更新.这是因为Image自带了c ...
- Android实现异步从网络加载图片列表
博文出处:http://blog.csdn.net/carterjin/article/details/7995935 有时会有在加载ListView的时候,包含用户头像或其他需要到网络获取的图 ...
- Android的轮播图Banner之本地加载和网络加载图片(含demo)
前言 关于轮播图 我个人是比较喜欢 闲来无事的时候 可以整理自己的照片 做一个demo 看看动态的效果 挺不错的! 每个App也基本都有一些广告位置 只要打开这个页面就会无限轮播广告图片 看多了我们也 ...
- iOS关于加载图片的几种方式选择
最近在开发过程中遇到一些性能优化的东西,这次来说说关于图片加载的性能优化和选择. 大家都知道创建UIImage常用以下几种方式 + (nullable UIImage *)imageNamed:(NS ...
- Android循环滚动广告条的完美实现,封装方便,平滑过渡,从网络加载图片,点击广告进入对应网址
关注finddreams,一起分享,一起进步: http://blog.csdn.net/finddreams/article/details/44619589 今天给大家带来一点干货,就是横向循环滚 ...
- LruCache:从网络加载图片缓存实例
OOM异常 堆内存用于存储实例对象,当程序不断创建对象,并且对象都有引用指向,那么垃圾回收机制就不会清理这些对象,当对象多到挤满堆内存的上限后,就产生OOM异常.Android系统为每个应用程序使用的 ...
- ios SDWebImage 加载图片流程
入口 setImageWithURL:placeholderImage:options: 会先把 placeholderImage 显示,然后 SDWebImageManager 根据 URL 开始处 ...
- 使用自定义的item、Adapter和AsyncTask、第三方开源框架PullToRefresh联合使用实现自定义的下拉列表(从网络加载图片显示在item中的ImageView)...
AsyncTask使用方法详情:http://www.cnblogs.com/zzw1994/p/4959949.html 下拉开源框架PullToRefresh使用方法和下载详情:http://ww ...
最新文章
- 微服务平台的发展趋势
- MVC分页控件之二,为IQueryable定义一个扩展方法,直接反回PagedListT结果集
- 死磕Java并发:J.U.C之Condition
- python 生成时间序列
- Vue 学习第八天
- Net 5.0 快速开发框架 YC.Boilerplate--框架介绍
- l启动进程 linux,《日子》. linux 查看进程启动路径
- 调用gensim库训练word2vec词向量
- MacBook Pro、iPad所需OLED屏幕有望由三星供应
- Eclipse智能感知功能优化
- 微服务框架和工具大全
- 《自己动手写操作系统 》第九章 一 简易硬盘驱动的实现
- java架构师主要是干什么的,要注意什么?
- 【word毕业论文排版(1)】尾注的删除
- 数据库设计各阶段任务
- UWB定位系统会存在定位误差吗?
- 中国DNS解析出现大规模故障
- 想去微软工作吗?这些岗位年薪超过1100000元
- 不可重现的bug如何处理
- 【转】Android-Input 键盘设备
热门文章
- c python 传参数 数组_python函数传递数组参数吗
- leetcode - 206. 反转链表
- 计蒜客——数位反转问题(代码+解析)
- STM32 - 高级定时器的设定 - 基础-05 - 输出波形控制 -Complementary outputs and dead-time insertion 相位调整@互补输出和死区控制
- 蔡高厅老师 - 高等数学阅读笔记 - 13 不定积分 - 02 分部积分 - 积分函数(53 - 58)
- 【高级】小程序 - 腾讯云 - wafer - PHP - 数据库接口的应用和研究 - 02 - DB::select - 正确的接口写法 - 包括布尔判断
- ad17 pcb扇孔_PCB设计中为什么需要先进行扇孔
- python 拟牛顿法 求非线性方程_C语言实现迭代法求非线性方程的根
- pythonfor循环输入_Python之for循环的使用
- 还在维护吗_你的模具生锈了吗?来了解一下这些防锈维护事项