转:http://blog.csdn.net/marujunyy/article/details/18424711
由于ASIHTTPRequest 不再更新了,不能使用block感觉不太好用;最后选择了AFNetWorking,并做了进一步的封装。
需要导入的framework:CFNetwork、Security、SystemConfiguration、MobileCoreServices
GitHub:https://github.com/AFNetworking/AFNetworking
最新的版本为2.0支持iOS 6.0以上系统,在iOS 5上可能报错:Property with 'retain (or strong)' attribute must be of object type
下面是封装的类:
// HttpManager.h
- //
- //HttpManager.h
- //HLMagic
- //
- //Createdbymarujunon14-1-17.
- //Copyright(c)2014年jizhi.Allrightsreserved.
- //
- #import<Foundation/Foundation.h>
- #import<CommonCrypto/CommonDigest.h>
- #import"AFNetworking.h"
- #import"Reachability.h"
- @interfaceNSString(HttpManager)
- -(NSString*)md5;
- -(NSString*)encode;
- -(NSString*)decode;
- -(NSString*)object;
- @end
- @interfaceNSObject(HttpManager)
- -(NSString*)json;
- @end
- @interfaceHttpManager:NSObject
- +(HttpManager*)defaultManager;
- /*-------判断当前的网络类型----------
- 1、NotReachable-没有网络连接
- 2、ReachableViaWWAN-移动网络(2G、3G)
- 3、ReachableViaWiFi-WIFI网络
- */
- +(NetworkStatus)networkStatus;
- //GET请求
- -(void)getRequestToUrl:(NSString*)urlparams:(NSDictionary*)paramscomplete:(void(^)(BOOLsuccessed,NSDictionary*result))complete;
- -(void)getCacheToUrl:(NSString*)urlparams:(NSDictionary*)paramscomplete:(void(^)(BOOLsuccessed,NSDictionary*result))complete;//请求失败时使用缓存数据
- //POST请求
- -(void)postRequestToUrl:(NSString*)urlparams:(NSDictionary*)paramscomplete:(void(^)(BOOLsuccessed,NSDictionary*result))complete;
- /*
- files:需要上传的文件数组,数组里为多个字典
- 字典里的key:
- 1、name:文件名称(如:demo.jpg)
- 2、file:文件(支持四种数据类型:NSData、UIImage、NSURL、NSString)NSURL、NSString为文件路径
- 3、type:文件类型(默认:image/jpeg)
- 示例:@[@{@"file":_headImg.currentBackgroundImage,@"name":@"head.jpg"}];
- */
- //AFHTTPRequestOperation可以暂停、重新开启、取消[operationpause]、[operationresume];、[operationcancel];
- -(AFHTTPRequestOperation*)uploadToUrl:(NSString*)url
- params:(NSDictionary*)params
- files:(NSArray*)files
- complete:(void(^)(BOOLsuccessed,NSDictionary*result))complete;
- //可以查看进度process_block
- -(AFHTTPRequestOperation*)uploadToUrl:(NSString*)url
- params:(NSDictionary*)params
- files:(NSArray*)files
- process:(void(^)(NSIntegerwritedBytes,NSIntegertotalBytes))process
- complete:(void(^)(BOOLsuccessed,NSDictionary*result))complete;
- /*
- filePath:下载文件的存储路径
- response:接口返回的不是文件而是json数据
- process:进度
- */
- -(AFHTTPRequestOperation*)downloadFromUrl:(NSString*)url
- filePath:(NSString*)filePath
- complete:(void(^)(BOOLsuccessed,NSDictionary*response))complete;
- -(AFHTTPRequestOperation*)downloadFromUrl:(NSString*)url
- params:(NSDictionary*)params
- filePath:(NSString*)filePath
- process:(void(^)(NSIntegerreadBytes,NSIntegertotalBytes))process
- complete:(void(^)(BOOLsuccessed,NSDictionary*response))complete;
- @end
//"HttpManager.m"
- //
- //HttpManager.m
- //HLMagic
- //
- //Createdbymarujunon14-1-17.
- //Copyright(c)2014年jizhi.Allrightsreserved.
- //
- #import"HttpManager.h"
- @implementationNSString(HttpManager)
- -(NSString*)md5
- {
- if(self==nil||[selflength]==0){
- returnnil;
- }
- constchar*value=[selfUTF8String];
- unsignedcharoutputBuffer[CC_MD5_DIGEST_LENGTH];
- CC_MD5(value,(CC_LONG)strlen(value),outputBuffer);
- NSMutableString*outputString=[[NSMutableStringalloc]initWithCapacity:CC_MD5_DIGEST_LENGTH*2];
- for(NSIntegercount=0;count<CC_MD5_DIGEST_LENGTH;count++){
- [outputStringappendFormat:@"%02x",outputBuffer[count]];
- }
- returnoutputString;
- }
- -(NSString*)encode
- {
- NSString*outputStr=(NSString*)
- CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
- (CFStringRef)self,
- NULL,
- NULL,
- kCFStringEncodingUTF8));
- returnoutputStr;
- }
- -(NSString*)decode
- {
- NSMutableString*outputStr=[NSMutableStringstringWithString:self];
- [outputStrreplaceOccurrencesOfString:@"+"withString:@""options:NSLiteralSearchrange:NSMakeRange(0,[outputStrlength])];
- return[outputStrstringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
- }
- -(id)object
- {
- idobject=nil;
- @try{
- NSData*data=[selfdataUsingEncoding:NSUTF8StringEncoding];;
- object=[NSJSONSerializationJSONObjectWithData:dataoptions:NSJSONReadingMutableLeaveserror:nil];
- }
- @catch(NSException*exception){
- NSLog(@"%s[Line%d]JSON字符串转换成对象出错了--> %@",__PRETTY_FUNCTION__,__LINE__,exception);
- }
- @finally{
- }
- returnobject;
- }
- @end
- @implementationNSObject(HttpManager)
- -(NSString*)json
- {
- NSString*jsonStr=@"";
- @try{
- NSData*jsonData=[NSJSONSerializationdataWithJSONObject:selfoptions:0error:nil];
- jsonStr=[[NSStringalloc]initWithData:jsonDataencoding:NSUTF8StringEncoding];
- }
- @catch(NSException*exception){
- NSLog(@"%s[Line%d]对象转换成JSON字符串出错了--> %@",__PRETTY_FUNCTION__,__LINE__,exception);
- }
- @finally{
- }
- returnjsonStr;
- }
- @end
- @interfaceHttpManager()
- {
- AFHTTPRequestOperationManager*operationManager;
- }
- @end
- @implementationHttpManager
- -(id)init{
- self=[superinit];
- if(self){
- operationManager=[AFHTTPRequestOperationManagermanager];
- operationManager.responseSerializer.acceptableContentTypes=nil;
- NSURLCache*urlCache=[NSURLCachesharedURLCache];
- [urlCachesetMemoryCapacity:5*1024*1024];/*设置缓存的大小为5M*/
- [NSURLCachesetSharedURLCache:urlCache];
- }
- returnself;
- }
- +(HttpManager*)defaultManager
- {
- staticdispatch_once_tpred=0;
- __strongstaticiddefaultHttpManager=nil;
- dispatch_once(&pred,^{
- defaultHttpManager=[[selfalloc]init];
- });
- returndefaultHttpManager;
- }
- -(void)getRequestToUrl:(NSString*)urlparams:(NSDictionary*)paramscomplete:(void(^)(BOOLsuccessed,NSDictionary*result))complete
- {
- [selfrequestToUrl:urlmethod:@"GET"useCache:NOparams:paramscomplete:complete];
- }
- -(void)getCacheToUrl:(NSString*)urlparams:(NSDictionary*)paramscomplete:(void(^)(BOOLsuccessed,NSDictionary*result))complete
- {
- [selfrequestToUrl:urlmethod:@"GET"useCache:YESparams:paramscomplete:complete];
- }
- -(void)postRequestToUrl:(NSString*)urlparams:(NSDictionary*)paramscomplete:(void(^)(BOOLsuccessed,NSDictionary*result))complete
- {
- [selfrequestToUrl:urlmethod:@"POST"useCache:NOparams:paramscomplete:complete];
- }
- -(void)requestToUrl:(NSString*)urlmethod:(NSString*)methoduseCache:(BOOL)useCache
- params:(NSDictionary*)paramscomplete:(void(^)(BOOLsuccessed,NSDictionary*result))complete
- {
- params=[[HttpManagergetRequestBodyWithParams:params]copy];
- AFHTTPRequestSerializer*serializer=[AFHTTPRequestSerializerserializer];
- NSMutableURLRequest*request=[serializerrequestWithMethod:methodURLString:urlparameters:paramserror:nil];
- [requestsetTimeoutInterval:10];
- if(useCache){
- [requestsetCachePolicy:NSURLRequestReturnCacheDataElseLoad];
- }
- void(^requestSuccessBlock)(AFHTTPRequestOperation*operation,idresponseObject)=^(AFHTTPRequestOperation*operation,idresponseObject){
- [selfshowMessageWithOperation:operationmethod:methodparams:params];
- complete?complete(true,responseObject):nil;
- };
- void(^requestFailureBlock)(AFHTTPRequestOperation*operation,NSError*error)=^(AFHTTPRequestOperation*operation,NSError*error){
- [selfshowMessageWithOperation:operationmethod:methodparams:params];
- complete?complete(false,nil):nil;
- };
- AFHTTPRequestOperation*operation=nil;
- if(useCache){
- operation=[selfcacheOperationWithRequest:requestsuccess:requestSuccessBlockfailure:requestFailureBlock];
- }else{
- operation=[operationManagerHTTPRequestOperationWithRequest:requestsuccess:requestSuccessBlockfailure:requestFailureBlock];
- }
- [operationManager.operationQueueaddOperation:operation];
- }
- -(AFHTTPRequestOperation*)cacheOperationWithRequest:(NSURLRequest*)urlRequest
- success:(void(^)(AFHTTPRequestOperation*operation,idresponseObject))success
- failure:(void(^)(AFHTTPRequestOperation*operation,NSError*error))failure
- {
- AFHTTPRequestOperation*operation=[operationManagerHTTPRequestOperationWithRequest:urlRequestsuccess:^(AFHTTPRequestOperation*operation,idresponseObject){
- NSCachedURLResponse*cachedURLResponse=[[NSURLCachesharedURLCache]cachedResponseForRequest:urlRequest];
- //storeincache
- cachedURLResponse=[[NSCachedURLResponsealloc]initWithResponse:operation.responsedata:operation.responseDatauserInfo:nilstoragePolicy:NSURLCacheStorageAllowed];
- [[NSURLCachesharedURLCache]storeCachedResponse:cachedURLResponseforRequest:urlRequest];
- success(operation,responseObject);
- }failure:^(AFHTTPRequestOperation*operation,NSError*error){
- if(error.code==kCFURLErrorNotConnectedToInternet){
- NSCachedURLResponse*cachedResponse=[[NSURLCachesharedURLCache]cachedResponseForRequest:urlRequest];
- if(cachedResponse!=nil&&[[cachedResponsedata]length]>0){
- success(operation,cachedResponse.data);
- }else{
- failure(operation,error);
- }
- }else{
- failure(operation,error);
- }
- }];
- returnoperation;
- }
- -(AFHTTPRequestOperation*)uploadToUrl:(NSString*)url
- params:(NSDictionary*)params
- files:(NSArray*)files
- complete:(void(^)(BOOLsuccessed,NSDictionary*result))complete
- {
- return[selfuploadToUrl:urlparams:paramsfiles:filesprocess:nilcomplete:complete];
- }
- -(AFHTTPRequestOperation*)uploadToUrl:(NSString*)url
- params:(NSDictionary*)params
- files:(NSArray*)files
- process:(void(^)(NSIntegerwritedBytes,NSIntegertotalBytes))process
- complete:(void(^)(BOOLsuccessed,NSDictionary*result))complete
- {
- params=[[HttpManagergetRequestBodyWithParams:params]copy];
- FLOG(@"postrequesturl:%@ postparams:%@",url,params);
- AFHTTPRequestSerializer*serializer=[AFHTTPRequestSerializerserializer];
- NSMutableURLRequest*request=[serializermultipartFormRequestWithMethod:@"POST"URLString:urlparameters:paramsconstructingBodyWithBlock:^(id<AFMultipartFormData>formData){
- for(NSDictionary*fileIteminfiles){
- idvalue=[fileItemobjectForKey:@"file"];//支持四种数据类型:NSData、UIImage、NSURL、NSString
- NSString*name=@"file";//字段名称
- NSString*fileName=[fileItemobjectForKey:@"name"];//文件名称
- NSString*mimeType=[fileItemobjectForKey:@"type"];//文件类型
- mimeType=mimeType?mimeType:@"image/jpeg";
- if([valueisKindOfClass:[NSDataclass]]){
- [formDataappendPartWithFileData:valuename:namefileName:fileNamemimeType:mimeType];
- }elseif([valueisKindOfClass:[UIImageclass]]){
- if(UIImagePNGRepresentation(value)){//返回为png图像。
- [formDataappendPartWithFileData:UIImagePNGRepresentation(value)name:namefileName:fileNamemimeType:mimeType];
- }else{//返回为JPEG图像。
- [formDataappendPartWithFileData:UIImageJPEGRepresentation(value,0.5)name:namefileName:fileNamemimeType:mimeType];
- }
- }elseif([valueisKindOfClass:[NSURLclass]]){
- [formDataappendPartWithFileURL:valuename:namefileName:fileNamemimeType:mimeTypeerror:nil];
- }elseif([valueisKindOfClass:[NSStringclass]]){
- [formDataappendPartWithFileURL:[NSURLURLWithString:value]name:namefileName:fileNamemimeType:mimeTypeerror:nil];
- }
- }
- }error:nil];
- AFHTTPRequestOperation*operation=nil;
- operation=[operationManagerHTTPRequestOperationWithRequest:request
- success:^(AFHTTPRequestOperation*operation,idresponseObject){
- FLOG(@"postresponseObject:%@",responseObject);
- if(complete){
- complete(true,responseObject);
- }
- }failure:^(AFHTTPRequestOperation*operation,NSError*error){
- FLOG(@"posterror:%@",error);
- if(complete){
- complete(false,nil);
- }
- }];
- [operationsetUploadProgressBlock:^(NSUIntegerbytesWritten,NSIntegertotalBytesWritten,NSIntegertotalBytesExpectedToWrite){
- FLOG(@"uploadprocess:%.2d%%(%ld/%ld)",100*totalBytesWritten/totalBytesExpectedToWrite,(long)totalBytesWritten,(long)totalBytesExpectedToWrite);
- if(process){
- process(totalBytesWritten,totalBytesExpectedToWrite);
- }
- }];
- [operationstart];
- returnoperation;
- }
- -(AFHTTPRequestOperation*)downloadFromUrl:(NSString*)url
- filePath:(NSString*)filePath
- complete:(void(^)(BOOLsuccessed,NSDictionary*response))complete
- {
- return[selfdownloadFromUrl:urlparams:nilfilePath:filePathprocess:nilcomplete:complete];
- }
- -(AFHTTPRequestOperation*)downloadFromUrl:(NSString*)url
- params:(NSDictionary*)params
- filePath:(NSString*)filePath
- process:(void(^)(NSIntegerreadBytes,NSIntegertotalBytes))process
- complete:(void(^)(BOOLsuccessed,NSDictionary*response))complete
- {
- params=[[HttpManagergetRequestBodyWithParams:params]copy];
- AFHTTPRequestSerializer*serializer=[AFHTTPRequestSerializerserializer];
- NSMutableURLRequest*request=[serializerrequestWithMethod:@"GET"URLString:urlparameters:paramserror:nil];
- FLOG(@"getrequesturl:%@",[request.URL.absoluteStringdecode]);
- AFHTTPRequestOperation*operation=[[AFHTTPRequestOperationalloc]initWithRequest:request];
- operation.responseSerializer.acceptableContentTypes=nil;
- NSString*tmpPath=[filePathstringByAppendingString:@".tmp"];
- operation.outputStream=[[NSOutputStreamalloc]initToFileAtPath:tmpPathappend:NO];
- [operationsetCompletionBlockWithSuccess:^(AFHTTPRequestOperation*operation,idresponseObject){
- NSArray*mimeTypeArray=@[@"text/html",@"application/json"];
- NSError*moveError=nil;
- if([mimeTypeArraycontainsObject:operation.response.MIMEType]){
- //返回的是json格式数据
- responseObject=[NSDatadataWithContentsOfFile:tmpPath];
- responseObject=[NSJSONSerializationJSONObjectWithData:responseObjectoptions:2error:nil];
- [[NSFileManagerdefaultManager]removeItemAtPath:tmpPatherror:nil];
- FLOG(@"getresponseObject:%@",responseObject);
- }else{
- [[NSFileManagerdefaultManager]removeItemAtPath:filePatherror:nil];
- [[NSFileManagerdefaultManager]moveItemAtPath:tmpPathtoPath:filePatherror:&moveError];
- }
- if(complete&&!moveError){
- complete(true,responseObject);
- }else{
- complete?complete(false,responseObject):nil;
- }
- }failure:^(AFHTTPRequestOperation*operation,NSError*error){
- FLOG(@"geterror:%@",error);
- [[NSFileManagerdefaultManager]removeItemAtPath:tmpPatherror:nil];
- if(complete){
- complete(false,nil);
- }
- }];
- [operationsetDownloadProgressBlock:^(NSUIntegerbytesRead,NSIntegertotalBytesRead,NSIntegertotalBytesExpectedToRead){
- FLOG(@"downloadprocess:%.2d%%(%ld/%ld)",100*totalBytesRead/totalBytesExpectedToRead,(long)totalBytesRead,(long)totalBytesExpectedToRead);
- if(process){
- process(totalBytesRead,totalBytesExpectedToRead);
- }
- }];
- [operationstart];
- returnoperation;
- }
- +(NSMutableDictionary*)getRequestBodyWithParams:(NSDictionary*)params
- {
- NSMutableDictionary*requestBody=params?[paramsmutableCopy]:[[NSMutableDictionaryalloc]init];
- for(NSString*keyin[paramsallKeys]){
- idvalue=[paramsobjectForKey:key];
- if([valueisKindOfClass:[NSDateclass]]){
- [requestBodysetValue:@([valuetimeIntervalSince1970]*1000)forKey:key];
- }
- if([valueisKindOfClass:[NSDictionaryclass]]||[valueisKindOfClass:[NSArrayclass]]){
- [requestBodysetValue:[valuejson]forKey:key];
- }
- }
- NSString*token=[[NSUserDefaultsstandardUserDefaults]objectForKey:@"token"];
- if(token){
- [requestBodysetObject:tokenforKey:@"token"];
- }
- [requestBodysetObject:@"ios"forKey:@"genus"];
- returnrequestBody;
- }
- +(NetworkStatus)networkStatus
- {
- Reachability*reachability=[ReachabilityreachabilityWithHostname:@"www.apple.com"];
- //NotReachable-没有网络连接
- //ReachableViaWWAN-移动网络(2G、3G)
- //ReachableViaWiFi-WIFI网络
- return[reachabilitycurrentReachabilityStatus];
- }
- -(void)showMessageWithOperation:(AFHTTPRequestOperation*)operationmethod:(NSString*)methodparams:(NSDictionary*)params
- {
- NSString*urlAbsoluteString=[operation.request.URL.absoluteStringdecode];
- if([[methoduppercaseString]isEqualToString:@"GET"]){
- FLOG(@"getrequesturl:%@ ",urlAbsoluteString);
- }else{
- FLOG(@"%@requesturl:%@ postparams:%@ ",[methodlowercaseString],urlAbsoluteString,params);
- }
- if(operation.error){
- FLOG(@"%@error:%@",[methodlowercaseString],operation.error);
- }else{
- FLOG(@"%@responseObject:%@",[methodlowercaseString],operation.responseObject);
- }
- ////只显示一部分url
- //NSArray*ignordUrls=@[url_originalDataDownload,url_originalDataUpload,url_originalDataUploadFinished,url_getEarliestOriginalData,url_newVersion,
- //url_saveSyncFailInfo];
- //for(NSString*ignordUrlinignordUrls){
- //if([urlAbsoluteStringrangeOfString:ignordUrl].length){
- //return;
- //}
- //}
- ////弹出网络提示
- //if(!operation.error){
- //if([operation.responseObjectobjectForKey:@"msg"]&&[[operation.responseObjectobjectForKey:@"msg"]length]){
- //[KeyWindowshowAlertMessage:[operation.responseObjectobjectForKey:@"msg"]callback:nil];
- //}
- //}
- //else{
- //if(operation.error.code==kCFURLErrorNotConnectedToInternet){
- //[KeyWindowshowAlertMessage:@"您已断开网络连接"callback:nil];
- //}else{
- //[KeyWindowshowAlertMessage:@"服务器忙,请稍后再试"callback:nil];
- //}
- //}
- }
- @end
图片缓存类,用于缓存图片;并写了UIImageView和UIButton的扩展方法;可直接设置其对应图片的URL。
// ImageCache.h
- //
- //ImageCache.h
- //CoreDataUtil
- //
- //Createdbymarujunon14-1-18.
- //Copyright(c)2014年jizhi.Allrightsreserved.
- //
- #import<UIKit/UIKit.h>
- #import<UIKit/UIImageView.h>
- #import<UIKit/UIButton.h>
- #import<objc/runtime.h>
- #defineADD_DYNAMIC_PROPERTY(PROPERTY_TYPE,PROPERTY_NAME,SETTER_NAME)
- @dynamicPROPERTY_NAME;
- staticcharkProperty##PROPERTY_NAME;
- -(PROPERTY_TYPE)PROPERTY_NAME{
- return(PROPERTY_TYPE)objc_getAssociatedObject(self,&(kProperty##PROPERTY_NAME));
- }
- -(void)SETTER_NAME:(PROPERTY_TYPE)PROPERTY_NAME{
- objc_setAssociatedObject(self,&kProperty##PROPERTY_NAME,PROPERTY_NAME,OBJC_ASSOCIATION_RETAIN);
- }
- @interfaceUIImage(ImageCache)
- @property(nonatomic,strong)NSString*lastCacheUrl;
- /*********************----------*****************************
- 1、UIImage的扩展方法,用于缓存图片;如果图片已下载则使用本地图片
- 2、下载完成之后会执行回调,并可查看下载进度
- ********************----------******************************/
- +(void)imageWithURL:(NSString*)urlcallback:(void(^)(UIImage*image))callback;
- +(void)imageWithURL:(NSString*)url
- process:(void(^)(NSIntegerreadBytes,NSIntegertotalBytes))process
- callback:(void(^)(UIImage*image))callback;
- /*通过URL获取缓存图片在本地对应的路径*/
- +(NSString*)getImagePathWithURL:(NSString*)url;
- @end
- @interfaceUIImageView(ImageCache)
- @property(nonatomic,strong)NSString*lastCacheUrl;
- /*设置UIImageView的图片的URL,下载失败设置图片为空*/
- -(void)setImageURL:(NSString*)url;
- /*设置UIImageView的图片的URL,下载失败则使用默认图片设置*/
- -(void)setImageURL:(NSString*)urldefaultImage:(UIImage*)defaultImage;
- /*设置UIImageView的图片的URL,下载完成之后先设置图片然后执行回调函数*/
- -(void)setImageURL:(NSString*)urlcallback:(void(^)(UIImage*image))callback;
- @end
- @interfaceUIButton(ImageCache)
- @property(nonatomic,strong)NSString*lastCacheUrl;
- /*设置按钮的图片的URL,下载失败设置图片为空*/
- -(void)setImageURL:(NSString*)urlforState:(UIControlState)state;
- /*设置按钮的图片的URL,下载失败则使用默认图片设置*/
- -(void)setImageURL:(NSString*)urlforState:(UIControlState)statedefaultImage:(UIImage*)defaultImage;
- /*设置按钮的图片的URL,下载完成之后先设置图片然后执行回调函数*/
- -(void)setImageURL:(NSString*)urlforState:(UIControlState)statecallback:(void(^)(UIImage*image))callback;
- /*设置按钮的背景图片的URL,下载失败设置图片为空*/
- -(void)setBackgroundImageURL:(NSString*)urlforState:(UIControlState)state;
- /*设置按钮的背景图片的URL,下载失败则使用默认图片设置*/
- -(void)setBackgroundImageURL:(NSString*)urlforState:(UIControlState)statedefaultImage:(UIImage*)defaultImage;
- /*设置按钮的背景图片的URL,下载完成之后先设置图片然后执行回调函数*/
- -(void)setBackgroundImageURL:(NSString*)urlforState:(UIControlState)statecallback:(void(^)(UIImage*image))callback;
- @end
// ImageCache.m
- //
- //ImageCache.m
- //CoreDataUtil
- //
- //Createdbymarujunon14-1-18.
- //Copyright(c)2014年jizhi.Allrightsreserved.
- //
- #import"ImageCache.h"
- #import"HttpManager.h"
- staticNSMutableArray*downloadTaskArray_ImageCache;
- staticBOOLisDownloading_ImageCache;
- @implementationUIImage(ImageCache)
- ADD_DYNAMIC_PROPERTY(NSString*,lastCacheUrl,setLastCacheUrl);
- +(void)imageWithURL:(NSString*)urlcallback:(void(^)(UIImage*image))callback
- {
- [selfimageWithURL:urlprocess:nilcallback:callback];
- }
- +(void)imageWithURL:(NSString*)url
- process:(void(^)(NSIntegerreadBytes,NSIntegertotalBytes))process
- callback:(void(^)(UIImage*image))callback
- {
- if(!downloadTaskArray_ImageCache){
- downloadTaskArray_ImageCache=[[NSMutableArrayalloc]init];
- }
- NSString*filePath=[selfgetImagePathWithURL:url];
- if([[NSFileManagerdefaultManager]fileExistsAtPath:filePath]){
- UIImage*lastImage=[UIImageimageWithContentsOfFile:filePath];
- lastImage.lastCacheUrl=url?url:@"";
- callback?callback(lastImage):nil;
- }else{
- NSMutableDictionary*task=[[NSMutableDictionaryalloc]init];
- url?[tasksetObject:urlforKey:@"url"]:nil;
- process?[tasksetObject:processforKey:@"process"]:nil;
- callback?[tasksetObject:callbackforKey:@"callback"]:nil;
- [downloadTaskArray_ImageCacheaddObject:task];
- [selfstartDownload];
- }
- }
- +(void)startDownload
- {
- if(downloadTaskArray_ImageCache.count&&!isDownloading_ImageCache){
- NSDictionary*lastObj=[downloadTaskArray_ImageCachelastObject];
- [selfdownloadWithURL:lastObj[@"url"]process:lastObj[@"process"]callback:lastObj[@"callback"]];
- }
- }
- +(void)downloadWithURL:(NSString*)url
- process:(void(^)(NSIntegerreadBytes,NSIntegertotalBytes))process
- callback:(void(^)(UIImage*image))callback
- {
- NSString*filePath=[selfgetImagePathWithURL:url];
- NSMutableDictionary*task=[[NSMutableDictionaryalloc]init];
- url?[tasksetObject:urlforKey:@"url"]:nil;
- process?[tasksetObject:processforKey:@"process"]:nil;
- callback?[tasksetObject:callbackforKey:@"callback"]:nil;
- isDownloading_ImageCache=true;
- if([[NSFileManagerdefaultManager]fileExistsAtPath:filePath]){
- UIImage*lastImage=[UIImageimageWithContentsOfFile:filePath];
- lastImage.lastCacheUrl=url?url:@"";
- callback?callback(lastImage):nil;
- [downloadTaskArray_ImageCacheremoveObject:task];
- isDownloading_ImageCache=false;
- [selfstartDownload];
- }else{
- [[HttpManagerdefaultManager]downloadFromUrl:url
- params:nil
- filePath:filePath
- process:process
- complete:^(BOOLsuccessed,NSDictionary*result){
- if(callback){
- if(successed&&!result){
- UIImage*lastImage=[UIImageimageWithContentsOfFile:filePath];
- lastImage.lastCacheUrl=url?url:@"";
- callback?callback(lastImage):nil;
- }else{
- callback(nil);
- }
- }
- [downloadTaskArray_ImageCacheremoveObject:task];
- isDownloading_ImageCache=false;
- [selfstartDownload];
- }];
- }
- }
- +(NSString*)getImagePathWithURL:(NSString*)url
- {
- //先创建个缓存文件夹
- NSString*directory=[NSHomeDirectory()stringByAppendingPathComponent:@"Library/Caches/imgcache"];
- NSFileManager*defaultManager=[NSFileManagerdefaultManager];
- if(![defaultManagerfileExistsAtPath:directory]){
- [defaultManagercreateDirectoryAtPath:directorywithIntermediateDirectories:YESattributes:nilerror:nil];
- }
- return[directorystringByAppendingPathComponent:[urlmd5]];
- }
- @end
- @implementationUIImageView(ImageCache)
- ADD_DYNAMIC_PROPERTY(NSString*,lastCacheUrl,setLastCacheUrl);
- -(void)setImageURL:(NSString*)url
- {
- [selfsetImageURL:urlcallback:nil];
- }
- -(void)setImageURL:(NSString*)urldefaultImage:(UIImage*)defaultImage
- {
- defaultImage?self.image=defaultImage:nil;
- self.lastCacheUrl=url;
- [UIImageimageWithURL:urlcallback:^(UIImage*image){
- if([image.lastCacheUrlisEqualToString:self.lastCacheUrl]){
- image?self.image=image:nil;
- }
- }];
- }
- -(void)setImageURL:(NSString*)urlcallback:(void(^)(UIImage*image))callback
- {
- self.lastCacheUrl=url;
- [UIImageimageWithURL:urlcallback:^(UIImage*image){
- if([image.lastCacheUrlisEqualToString:self.lastCacheUrl]){
- image?self.image=image:nil;
- }
- callback?callback(image):nil;
- }];
- }
- @end
- @implementationUIButton(ImageCache)
- ADD_DYNAMIC_PROPERTY(NSString*,lastCacheUrl,setLastCacheUrl);
- -(void)setImageURL:(NSString*)urlforState:(UIControlState)state
- {
- [selfsetImageURL:urlforState:statedefaultImage:nil];
- }
- -(void)setImageURL:(NSString*)urlforState:(UIControlState)statedefaultImage:(UIImage*)defaultImage
- {
- defaultImage?[selfsetImage:defaultImageforState:state]:nil;
- self.lastCacheUrl=url;
- [UIImageimageWithURL:urlcallback:^(UIImage*image){
- if([image.lastCacheUrlisEqualToString:self.lastCacheUrl]){
- image?[selfsetImage:imageforState:state]:nil;
- }
- }];
- }
- -(void)setImageURL:(NSString*)urlforState:(UIControlState)statecallback:(void(^)(UIImage*image))callback
- {
- self.lastCacheUrl=url;
- [UIImageimageWithURL:urlcallback:^(UIImage*image){
- if([image.lastCacheUrlisEqualToString:self.lastCacheUrl]){
- image?[selfsetImage:imageforState:state]:nil;
- }
- callback?callback(image):nil;
- }];
- }
- -(void)setBackgroundImageURL:(NSString*)urlforState:(UIControlState)state
- {
- [selfsetBackgroundImageURL:urlforState:statedefaultImage:nil];
- }
- -(void)setBackgroundImageURL:(NSString*)urlforState:(UIControlState)statedefaultImage:(UIImage*)defaultImage
- {
- defaultImage?[selfsetBackgroundImage:defaultImageforState:state]:nil;
- self.lastCacheUrl=url;
- [UIImageimageWithURL:urlcallback:^(UIImage*image){
- if([image.lastCacheUrlisEqualToString:self.lastCacheUrl]){
- image?[selfsetBackgroundImage:imageforState:state]:nil;
- }
- }];
- }
- -(void)setBackgroundImageURL:(NSString*)urlforState:(UIControlState)statecallback:(void(^)(UIImage*image))callback
- {
- self.lastCacheUrl=url;
- [UIImageimageWithURL:urlcallback:^(UIImage*image){
- if([image.lastCacheUrlisEqualToString:self.lastCacheUrl]){
- image?[selfsetBackgroundImage:imageforState:state]:nil;
- }
- callback?callback(image):nil;
- }];
- }
- @end
- /*使用示例*/
- NSString*url=@"http://b.hiphotos.baidu.com/image/w%3D2048/sign=4c2a6e019058d109c4e3aeb2e560cdbf/b812c8fcc3cec3fd6d7daa0ad488d43f87942709.jpg";
- //缓存图片
- //[UIImageimageWithURL:urlprocess:^(NSIntegerreadBytes,NSIntegertotalBytes){
- //NSLog(@"下载进度:%.0f%%",100*readBytes/totalBytes);
- //}callback:^(UIImage*image){
- //NSLog(@"图片下载完成!");
- //}];
- //设置UIImageView的图片,下载失败则使用默认图片
- UIImageView*imageView=[[UIImageViewalloc]initWithFrame:self.view.bounds];
- [imageViewsetImageURL:urldefaultImage:[UIImageimageNamed:@"default.png"]];
- imageView.contentMode=UIViewContentModeScaleAspectFit;
- [self.viewaddSubview:imageView];
- //设置UIButton的图片,下载失败则使用默认图片
- UIButton*button=[[UIButtonalloc]initWithFrame:self.view.bounds];
- [buttonsetImageURL:urlforState:UIControlStateNormaldefaultImage:[UIImageimageNamed:@"default.png"]];
- [self.viewaddSubview:button];
GitHub 地址:https://github.com/marujun/DataManager