自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

iOS網(wǎng)絡(luò)加載圖片緩存策略之ASIDownloadCache緩存優(yōu)化

移動(dòng)開(kāi)發(fā) iOS
在我們實(shí)際工程中,很多情況需要從網(wǎng)絡(luò)上加載圖片,然后將圖片在imageview中顯示出來(lái),但每次都要從網(wǎng)絡(luò)上請(qǐng)求,會(huì)嚴(yán)重影響用戶體驗(yàn),為了不是每次顯示都需要從網(wǎng)上下載數(shù)據(jù),希望將圖片放到本地緩存,因此我們需要一個(gè)好的的緩存策略,今天我將我在項(xiàng)目工程中的實(shí)際經(jīng)驗(yàn)分享給大家,我這里主要介紹一下強(qiáng)大的ASIHTTPRequest的緩存策略,以及使用方法。

在我們實(shí)際工程中,很多情況需要從網(wǎng)絡(luò)上加載圖片,然后將圖片在imageview中顯示出來(lái),但每次都要從網(wǎng)絡(luò)上請(qǐng)求,會(huì)嚴(yán)重影響用戶體驗(yàn),為了不是每次顯示都需要從網(wǎng)上下載數(shù)據(jù),希望將圖片放到本地緩存,因此我們需要一個(gè)好的的緩存策略,今天我將我在項(xiàng)目工程中的實(shí)際經(jīng)驗(yàn)分享給大家,我這里主要介紹一下強(qiáng)大的ASIHTTPRequest的緩存策略,以及使用方法:

下面是具體步驟:

一、設(shè)置緩存策略

首先在SplitDemoAppDelegate委托代理中,實(shí)現(xiàn)如下代碼:

在SplitDemoAppDelegate.h文件中,代碼如下:

  1. #import <UIKit/UIKit.h> 
  2.  
  3.   @class ASIDownloadCache; 
  4.   
  5.  @interface SplitDemoAppDelegate : NSObject <UIApplicationDelegate,UITabBarControllerDelegate> { 
  6.   
  7.     UIWindow *_window; 
  8.  
  9.      ASIDownloadCache*_downloadCache;            //下載緩存策略 
  10.   
  11.  } 
  12.  
  13.  @property (nonatomic, retain) ASIDownloadCache*downloadCache; 
  14.  
  15.  @end 

在SplitDemoAppDelegate.m文件中,代碼如下:

  1. #import "SplitDemoAppDelegate.h" 
  2.  
  3. @implementation SplitDemoAppDelegate 
  4.   
  5.   @synthesize window=_window; 
  6.  
  7. @synthesize downloadCache = _downloadCache; 
  8.  
  9.  - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions 
  10.   
  11.  { 
  12.  
  13.     //初始化ASIDownloadCache緩存對(duì)象 
  14.   
  15.    ASIDownloadCache *cache = [[ASIDownloadCache alloc] init]; 
  16.  
  17.     self.downloadCache = cache; 
  18.   
  19.    [cache release]; 
  20.  
  21.  
  22.     //路徑 
  23.   
  24.     NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES); 
  25.  
  26.   NSString *documentDirectory = [paths objectAtIndex:0]; 
  27.   
  28.     //設(shè)置緩存存放路徑 
  29.   
  30.    [self.downloadCache setStoragePath:[documentDirectorystringByAppendingPathComponent:@"resource"]]; 
  31.   
  32.     //設(shè)置緩存策略 
  33.   
  34.      [self.downloadCache setDefaultCachePolicy:ASIOnlyLoadIfNotCachedCachePolicy]; 
  35.   
  36.      // Override point for customization after application launch. 
  37.   
  38.      [self.window makeKeyAndVisible]; 
  39.  
  40.     return YES; 
  41.  
  42.  } 
  43.   
  44.  
  45.  - (void)dealloc 
  46.  
  47.   
  48.      [_window release]; 
  49.   
  50.      [_downloadCache release]; 
  51.   
  52.     [super dealloc]; 
  53.   
  54.  } 
  55.   
  56.  @end 

二、創(chuàng)建緩存線程

這一步是創(chuàng)建一個(gè)NSOperation類,實(shí)現(xiàn)緩存的方法,代碼如下:

ResourceContainer.h文件實(shí)現(xiàn):

  1. #import <Foundation/Foundation.h> 
  2.   
  3.   #import "ASIHTTPRequest.h" 
  4.   
  5. #import "SplitDemoAppDelegate.h" 
  6.  
  7.  @interface ResourceContainer : NSOperation { 
  8.  
  9. NSURL*_resourceURL;            //資源請(qǐng)求url 
  10.   
  11.  NSObject*_hostObject;              
  12.  
  13.  SEL_resourceDidReceive;      //資源接手響應(yīng)方法   
  14.  
  15.  SplitDemoAppDelegate*_appDelegate;            //應(yīng)用委托對(duì)象 
  16.   
  17.  ASIHTTPRequest*_httpRequest;             
  18.   
  19.  UIImageView*_imageView;               
  20.  
  21.  } 
  22.   
  23.  
  24.  
  25.  @property (nonatomic, retain) NSURL*resourceURL; 
  26.  
  27. @property (nonatomic, retain) NSObject*hostObject; 
  28.  
  29.  @property (nonatomic, assign) SELresourceDidReceive; 
  30.   
  31.  @property (nonatomic, assign) SplitDemoAppDelegate   *appDelegate; 
  32.   
  33.  @property (nonatomic, retain) ASIHTTPRequest*httpRequest; 
  34.  
  35.  @property (nonatomic, retain) UIImageView*imageView; 
  36.  
  37.    
  38.  
  39.  //http請(qǐng)求回調(diào)方法 
  40.  
  41.  -(void)didStartHttpRequest:(ASIHTTPRequest *)request; 
  42.   
  43.  -(void)didFinishHttpRequest:(ASIHTTPRequest *)request; 
  44.  
  45.  -(void)didFailedHttpRequest:(ASIHTTPRequest *)request; 
  46.   
  47.   
  48.  
  49. //取消資源請(qǐng)求 
  50.  
  51.  -(void)cancelReourceGet; 
  52.   
  53.  //資源接收回調(diào)方法 
  54.  
  55.  -(void)resourceDidReceive:(NSData *)resource; 
  56.  
  57.  @end 

ResourceContainer.m文件實(shí)現(xiàn):

  1. #import "ResourceContainer.h" 
  2.    #import "HttpConstant.h" 
  3.   #import "ASIDownloadCache.h" 
  4.  @implementation ResourceContainer 
  5.  @synthesize resourceURL = _resourceURL; 
  6.    @synthesize hostObject = _hostObject; 
  7.   @synthesize resourceDidReceive = _resourceDidReceive; 
  8.  @synthesize appDelegate = _appDelegate; 
  9.    @synthesize httpRequest = _httpRequest; 
  10.  @synthesize imageView = _imageView; 
  11.    
  12.   -(id)init{ 
  13.   
  14.       if(self == [super init]){ 
  15.    
  16.      self.appDelegate = (SplitDemoAppDelegate *)[[UIApplication        sharedApplication] delegate]; 
  17.   
  18.        } 
  19.   
  20.     return self; 
  21.    
  22.   } 
  23.    
  24.    
  25.   -(void)main{ 
  26.   
  27.       if(self.hostObject == nil) 
  28.       return
  29.    
  30.      if(self.resourceURL == nil){ 
  31.             [self resourceDidReceive:nil]; 
  32.            return
  33.       } 
  34.    
  35.        ASIHTTPRequest *request = [ASIHTTPRequest     requestWithURL:self.resourceURL] 
  36.       self.httpRequest = request; 
  37.  
  38.    
  39.   
  40.  [self.httpRequest setDownloadCache:self.appDelegate.downloadCache]; 
  41.   [self.httpRequest setDelegate:self]; 
  42.   [self.httpRequest setDidStartSelector:@selector(didStartHttpRequest:)]; 
  43.   [self.httpRequest setDidFinishSelector:@selector(didFinishHttpRequest:)]; 
  44.  [self.httpRequest setDidFailSelector:@selector(didFailedHttpRequest:)]; 
  45.  
  46.      //發(fā)異步請(qǐng)求 
  47.    
  48.  [self.httpRequest startAsynchronous]; 
  49.   
  50.  } 
  51.    
  52.  - (void)dealloc { 
  53.    
  54.  [_resourceURL release]; 
  55.  [_hostObject release]; 
  56.  [_httpRequest release]; 
  57.  [_imageView release]; 
  58.   [super dealloc]; 
  59.   
  60.  
  61.  //開(kāi)始請(qǐng)求 
  62.  
  63.  -(void)didStartHttpRequest:(ASIHTTPRequest *)request{ 
  64.   
  65.   [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES]; 
  66.  
  67.   } 
  68.  
  69.   //請(qǐng)求成功返回處理結(jié)果 
  70.  
  71.   -(void)didFinishHttpRequest:(ASIHTTPRequest *)request{ 
  72.   
  73.  [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO]; 
  74.   
  75.    
  76.  
  77.      if([request responseStatusCode] == 200 || [request responseStatusCode] == 304){ 
  78.  
  79.  //判斷是否來(lái)自緩存 
  80.  
  81.          if([request didUseCachedResponse]){ 
  82.   
  83.   NSLog(@"=========資源請(qǐng)求:%@ 來(lái)自緩存============",[self.resourceURL absoluteURL]); 
  84.    
  85.         } 
  86.          else
  87.              NSLog(@"=========資源請(qǐng)求:圖片不來(lái)自緩存============"); 
  88.         } 
  89.   
  90.   
  91.       [self resourceDidReceive:[request responseData]]; 
  92.  
  93.  } 
  94.   
  95.  else { 
  96.  
  97.         [self resourceDidReceive:nil]; 
  98.  
  99.         } 
  100.  
  101.   
  102.  //失敗請(qǐng)求返回處理結(jié)果 
  103.  
  104.  -(void)didFailedHttpRequest:(ASIHTTPRequest *)request{ 
  105.  
  106. [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO]; 
  107.   
  108.  [self resourceDidReceive:nil]; 
  109.  
  110.  
  111. //取消資源請(qǐng)求 
  112.  
  113.  -(void)cancelReourceGet{ 
  114.  
  115.  [self.httpRequest cancel]; 
  116.  
  117.  } 
  118.  
  119.  //資源接收處理方法 
  120.  
  121.  -(void)resourceDidReceive:(NSData *)resource{ 
  122.  
  123.  if([self.hostObject respondsToSelector:self.resourceDidReceive]){ 
  124.  
  125.  if(resource != nil && self.imageView != nil){ 
  126.  
  127.  self.imageView.image = [UIImage imageWithData:resource]; 
  128.  
  129.  
  130.   
  131.  [self.hostObject performSelectorOnMainThread:self.resourceDidReceive withObject:self.imageViewwaitUntilDone:NO]; 
  132.   
  133.   
  134.  } 
  135.  
  136.  @end  

到第二步,我們的緩存策略的設(shè)置,以及資源請(qǐng)求和接收數(shù)據(jù)方法已經(jīng)構(gòu)建完畢,下面介紹一下如何使用我們上面創(chuàng)建的NSOperation類

三、圖片請(qǐng)求(利用上面創(chuàng)建的類)

這里以我的工程為例進(jìn)行分析:

在DetailViewController.h聲明文件中:

  1. #import <UIKit/UIKit.h> 
  2.   
  3.   @interface DetailViewController :UIViewController { 
  4.   
  5.     NSURL                         *_imageURL;                    //圖片url 
  6.   
  7.     NSMutableArray            *_originalIndexArray;        //保存請(qǐng)求圖片的號(hào) 
  8.  
  9.     NSMutableDictionary     *_originalOperationDic;     //保存圖片請(qǐng)求隊(duì)列 
  10.  
  11.     NSOperationQueue        *_requestImageQueue;    //圖片請(qǐng)求隊(duì)列 
  12.  
  13.  
  14. @property (nonatomic, retain) NSURL                       *imageURL; 
  15.  @property (nonatomic, retain) NSMutableArray          *originalIndexArray; 
  16.  @property (nonatomic, retain) NSMutableDictionary   *originalOperationDic; 
  17.  @property (nonatomic, retain) NSOperationQueue      * requestImageQueue; 
  18.  
  19.  //顯示圖片信息 
  20.   
  21.  -(void)displayProductImage; 
  22.   
  23. //根據(jù)圖片序號(hào)顯示請(qǐng)求圖片資源 
  24.   
  25.  -(void)displayImageByIndex:(NSInteger)index ByImageURL:(NSURL *)url; 
  26.   
  27.  //處理圖片請(qǐng)求返回信息 
  28.  
  29.  -(void)imageDidReceive:(UIImageView *)imageView; 
  30.  
  31.  @end 

在DetailViewController.m實(shí)現(xiàn)文件中:

  1. #import "ProductDetailViewController.h" 
  2.    
  3.   //這里引入在第二步中,我們創(chuàng)建的對(duì)象 
  4.   #import "ResourceContainer.h" 
  5.   
  6.   @implementation DetailViewController 
  7.    @synthesize imageURL = _imageURL; 
  8.   @synthesize originalIndexArray = _originalIndexArray; 
  9.   @synthesize originalOperationDic = _originalOperationDic; 
  10.  @synthesize requestImageQueue = _requestImageQueue; 
  11.  
  12.   
  13.  - (void)viewDidLoad 
  14.  
  15.  { 
  16.   
  17.     [super viewDidLoad]; 
  18.       NSOperationQueue *tempQueue = [[NSOperationQueue alloc] init]; 
  19.   
  20.       self.requsetImageQueue = tempQueue; 
  21.       [tempQueue release]; 
  22.   
  23.        NSMutableArray *array = [[NSMutableArray alloc] init]; 
  24.  
  25.        self.originalIndexArray = array; 
  26.       [array release]; 
  27.   
  28.         NSMutableDictionary *dic = [[NSMutableDictionary alloc] init]; 
  29.    
  30.         self.originalOperationDic = dic; 
  31.          [dic release]; 
  32.    
  33.   } 
  34.    
  35.  //顯示圖片信息 
  36.    
  37.   -(void)displayProductImage 
  38.   
  39.   { 
  40.   
  41.      NSURL *url = [NSURL URLWithString:@"http://xxx.xxx.xxx.xxx"]; 
  42.  
  43.       //這個(gè)是從器返回有圖片數(shù)目,self.xxxx根據(jù)具體的場(chǎng)合 
  44.    
  45.       int imageCount = [self.xxxx.imageNum intValue]; 
  46.    
  47.       for (int i=0; i<imageCount; i++) { 
  48.    
  49.           NSString *str1 = @"這里是拼圖片請(qǐng)求url,根據(jù)實(shí)際需求"
  50.   
  51.          self.imageURL = [url URLByAppendingPathComponent:str1]; 
  52.   
  53.          //根據(jù)圖片號(hào)請(qǐng)求資源 
  54.   
  55.          [self displayImageByIndex:i ByImageURL:self.productImageURL]; 
  56.    
  57.      } 
  58.  
  59.  } 
  60.  
  61.   //根據(jù)圖片序號(hào)顯示請(qǐng)求圖片資源 
  62.   
  63. -(void) displayImageByIndex:(NSInteger)index ByImageURL:(NSURL *)url 
  64.   
  65.   { 
  66.   
  67.     NSString *indexForString = [NSString stringWithFormat:@"%d",index]; 
  68.   
  69.       //若數(shù)組中已經(jīng)存在該圖片編號(hào),說(shuō)明圖片加載完畢,直接返回 
  70.  
  71.     if ([self.originalIndexArray containsObject:indexForString]) { 
  72.   
  73.          return
  74.  
  75.      } 
  76.  
  77.      //創(chuàng)建UIImageView對(duì)象 
  78.   
  79.     UIImageView *imageView = [[UIImageView alloc] init]; 
  80.  
  81.      imageView.tag = index; 
  82.    
  83.     //創(chuàng)建資源請(qǐng)求對(duì)象 
  84.  
  85.      ResourceContainer  *imageOperation = [[ResourceContainer alloc] init]; 
  86.   
  87.       imageOperation.resourceURL = url; 
  88.  
  89.     imageOperation.hostObject = self; 
  90.  
  91.      //設(shè)置收到圖片信息處理理方法 
  92.  
  93.      imageOperation.resourceDidReceive = @selector(imageDidReceive:); 
  94.   
  95.     imageOperation.imageView = imageView; 
  96.   
  97.     [imageView release]; 
  98.  
  99.      //將圖片請(qǐng)求對(duì)象加入圖片請(qǐng)求隊(duì)列中 
  100.  
  101.     [self.requsetImageQueue addOperation:imageOperation]; 
  102.  
  103.     [self.originalOperationDic setObject:imageOperation forKey:indexForString]; 
  104.  
  105.     [imageOperation release]; 
  106.  
  107.   
  108. //處理圖片請(qǐng)求返回信息 
  109.  
  110.  -(void)imageDidReceive:(UIImageView *)imageView 
  111.  
  112.  { 
  113.  
  114.      if (imageView == nil||imageView.image == nil) { 
  115.  
  116.             imageView.image = [UIImage imageNamed:@"no-pic-300-250.png"]; 
  117.  
  118.      } 
  119.   
  120.      //將圖片信息加載到前臺(tái),self.openFlowView是我用的coverFlow,coverFlow的使用方法網(wǎng)上很多,自己找吧 
  121.  
  122.      [self.openFlowView setImage:imageView.image forIndex:imageView.tag]; 
  123.  
  124.     [self.originalIndexArray addObject:[NSString stringWithFormat:@"%d",imageView.tag]]; 
  125.  
  126.     [self.originalOperationDic removeObjectForKey:[NSString stringWithFormat:@"%d",imageView.tag]]; 
  127.  
  128.  } 
  129.  
  130. - (void)dealloc 
  131.  
  132.  { 
  133.       [_requestImageQueue release]; 
  134.   
  135.      [_originalIndexArray release]; 
  136.  
  137.      [_originalOperationDic release]; 
  138.  
  139.      [_imageURL release]; 
  140.  
  141.      [super dealloc]; 
  142.  
  143.  
  144. @end 

經(jīng)過(guò)上述步驟,我們實(shí)現(xiàn)了加載網(wǎng)絡(luò)圖片時(shí)緩存功能,增強(qiáng)了用戶體驗(yàn)效果。代碼中可能會(huì)有諸多問(wèn)題,希望網(wǎng)友指教,有更好的緩存方法,也希望一起交流!

責(zé)任編輯:張葉青 來(lái)源: 博客
相關(guān)推薦

2022-05-10 08:58:56

CacheHTTP

2015-06-11 10:12:26

Android圖片加載緩存

2014-04-17 10:56:40

優(yōu)化策略MySQL緩存

2023-11-16 08:22:14

LruCacheAndroid

2021-03-29 11:51:07

緩存儲(chǔ)存數(shù)據(jù)

2011-10-19 09:41:15

ASP.NET性能優(yōu)化

2020-06-11 13:03:04

性能優(yōu)化緩存

2019-03-20 09:11:50

Web緩存策略

2011-10-17 09:54:18

ASP.NET性能

2013-10-16 16:17:15

iOS開(kāi)發(fā)優(yōu)化方案

2015-10-08 16:40:50

緩存頭像策略

2018-03-27 09:28:33

緩存策略系統(tǒng)

2009-08-03 18:47:12

ASP.NET數(shù)據(jù)緩存

2024-07-23 08:06:19

緩存技術(shù)策略

2015-12-16 12:40:32

H5緩存機(jī)制移動(dòng)

2018-02-07 10:46:20

數(shù)據(jù)存儲(chǔ)

2020-07-16 08:04:21

瀏覽器緩存策略

2023-05-04 16:10:13

緩存前端

2024-05-06 12:20:00

緩存驅(qū)逐緩存

2017-05-05 10:13:03

應(yīng)用級(jí)緩存緩存代碼
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)