// .h文件
#import <Foundation/Foundation.h>
#import "ASIHTTPRequest.h"
#import "ASIDownloadCache.h"
typedef void (^MyBlock)(UIImage *image);
@interface AsyncDownLoading : NSObject
+ (id)ShareAsyncDownload;
- (void)LoadImageWithUrl:(NSString *)url;
@property (nonatomic, copy) MyBlock imageBlock;
@end
// .m文件
#import "AsyncDownLoading.h"
@implementation AsyncDownLoading
- (void)dealloc
{
Block_release(self.imageBlock);
[super dealloc];
}
+ (id)ShareAsyncDownload
{
static dispatch_once_t onceToken;
static AsyncDownLoading *downLoad = nil;
dispatch_once(&onceToken, ^{
downLoad=[[AsyncDownLoadingalloc] init];
});
return downLoad;
}
//暂时没有用
- (NSString *)cacheFileForImage:(NSString *)imageUrl
{
NSString *cacheFolder = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
cacheFolder = [cacheFolder stringByAppendingPathComponent:@"imagecache"];
NSFileManager *fmgr = [NSFileManagerdefaultManager];
if (![fmgr fileExistsAtPath:cacheFolder])
{
[fmgr createDirectoryAtPath:cacheFolder withIntermediateDirectories:YESattributes:nilerror:nil];
}
NSArray *paths = [imageUrl componentsSeparatedByString:@"/"];
NSString *saveStr = [[paths lastObject] length]>0?[paths lastObject]:@"";
return [NSString stringWithFormat:@"%@/%@",cacheFolder,saveStr];
}
- (void)LoadImageWithUrl:(NSString *)url
{
__block ASIHTTPRequest *Request = nil;
if (url)
{
Request = [ASIHTTPRequestrequestWithURL:[NSURLURLWithString:url]];
[Request setDelegate: self];
//设置下载缓存
[Request setDownloadCache:[ASIDownloadCachesharedCache]];
//设置缓存策略
[Request setCachePolicy:ASIOnlyLoadIfNotCachedCachePolicy];
//设置指定存储方式
[Request setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy];
//在后台也运行
[Request setShouldContinueWhenAppEntersBackground:YES];
[Request setTimeOutSeconds:60];
[Request setCompletionBlock:^{
if ([Request didUseCachedResponse])
{
NSLog(@"缓存");
}
else
{
NSLog(@"重新创建");
}
NSLog(@"--1--%@",[NSThreadcurrentThread]);
UIImage *image = [UIImageimageWithData:[Request responseData]];
self.imageBlock(image);
}];
[Request setFailedBlock:^{
NSLog(@"请求失败error-->%@",Request.error.localizedDescription);
}];
[Request startAsynchronous];
}
}
@end
//使用
AsyncDownLoading *down = [AsyncDownLoading ShareAsyncDownload];
down.imageBlock = ^(UIImage *image){
self.img1.image = image;
};
[down LoadImageWithUrl:@"http://h.hiphotos.baidu.com/album/w%3D2048/sign=45753fa7e850352ab1612208677bfaf2/2e2eb9389b504fc2aae48015e4dde71190ef6d62.jpg"];