Caching processing is a pretty headache, and you need to synthesize different strategies as needed. In general, there are several situations:
1.URL caching, such as post browsing for social apps, is a URL cache in Viewdidappear:. In simple terms, the Nsurlcache class is used, first in the APPDELEGATE.M.
-(BOOL) Application: (UIApplication *) application didfinishlaunchingwithoptions: (nsdictionary *) launchOptions method to create a Nsurlcache single example:
Set the memory cache size
Nsurlcache *urlcache = [[Nsurlcache alloc] initwithmemorycapacity:4 * 1024x768 * 1024x768 diskcapacity:10 * 1024x768 * 1024x768 diskpath:n IL];
[Nsurlcache Setsharedurlcache:urlcache];
Then the viewcontroller.m inside the implementation method:
Network Cache Response Method
-(Ibaction) Senderbutton: (ID) Sender {//Weather API Interfacensstring* Path =@"http://www.weather.com.cn/data/sk/101110101.html"; [Self Getbyurl:path andcallback:^(IDobj) {NSString*str =[[NSString alloc]initwithdata:obj encoding:nsutf8stringencoding]; NSLog (@"=========================================================\n"); NSLog (@"Post Cache test:%@", str); NSLog (@"=========================================================\n"); }];
}
Memory caching method for network requests
-(void) Getbyurl: (NSString *) path Andcallback: (CallBack) callback{nsstring* Pathstr =[path stringbyaddingpercentescapesusingencoding:nsutf8stringencoding]; Nsurl*url =[Nsurl Urlwithstring:pathstr]; Nsmutableurlrequest*request =[Nsmutableurlrequest Requestwithurl:url]; [Request Setcachepolicy:nsurlrequestreloadrevalidatingcachedata]; Nscachedurlresponse* Response =[[Nsurlcache Sharedurlcache] cachedresponseforrequest:request]; //determine if there is a cache if(Response! =Nil) {NSLog (@"have cache"); [Request Setcachepolicy:nsurlrequestreturncachedatadontload]; }Else{NSLog (@"No Cache"); } //Create Nsurlconnectionnsdata* data =[nsurlconnection sendsynchronousrequest:request returningresponse:nil Error:nil]; callback (data); }
2. File cache, such as user information and other basic unchanged information stored in the local sandbox
User information cache file saved in sandbox
-(Ibaction) Usercache: (UIButton *) Sender { = [self savefiletodocuments:@]/http www.weather.com.cn/data/sk/101020100.html"];}
//save file to sandbox-(NSString *) savefiletodocuments: (NSString *) url{NSString*resultfilepath =@""; NSString*destfilepath = [[Nshomedirectory () stringByAppendingPathComponent:@"Documents"] Stringbyappendingpathcomponent:url];//add URL, combine cost to file pathNSString *destfolderpath =[Destfilepath stringbydeletinglastpathcomponent]; //determines whether the path folder exists or does not exist to create if(![[Nsfilemanager Defaultmanager] Fileexistsatpath:destfolderpath]) {NSLog (@"folder does not exist, new folder"); [[Nsfilemanager Defaultmanager] createdirectoryatpath:destfolderpath withintermediatedirectories:yes attributes: Nil Error:nil]; } //determine if the file has been downloaded if([[[Nsfilemanager Defaultmanager] Fileexistsatpath:destfilepath]) {NSLog (@"file is downloaded \ n"); Resultfilepath=Destfilepath; } Else{NSLog (@"no cache, request data \ n"); NSData*userinfodata =[NSData Datawithcontentsofurl:[nsurl Urlwithstring:url]; if([Userinfodata writetofile:destfilepath Atomically:yes]) {Resultfilepath=Destfilepath; }} NSData*userinfodata=[[Nsfilemanager Defaultmanager] contentsatpath:resultfilepath]; NSString* str =[[NSString Alloc]initwithdata:userinfodata encoding:nsutf8stringencoding]; NSLog (@"=========================================================\n"); NSLog (@"user:%@", str); NSLog (@"=========================================================\n"); returnResultfilepath;}
3. Picture cache is the most important, the cost of traffic also accounted for memory, so we recommend the use of third-party sdwebimage
The simplest is to use this method:
[Self.imageview sd_setimagewithurl:url completed:^ (UIImage *image, Nserror *error, Sdimagecachetype cacheType, NSURL *ImageURL) { if(cachetype==Sdimagecachetypenone) {NSLog (@"no cache, download from network"); }Else if(cachetype==Sdimagecachetypedisk) {NSLog (@"have cache, read from disk"); }Else{NSLog (@"have cache, read from memory"); } }];
To know the internal mechanism of this method, see here.
Want to download this demo.
Reprint please specify the source!
Three ways IOS handles caching