ASIHTTPRequest是第三方類庫,ASIHTTPRequest對CFNetwork API進行了封裝。緩存
有以下特色:網絡
第1、同步請求:異步
ASIHTTPRequest *httpRequest=[ASIHTTPRequest requestWithURL:url];
[httpRequest setRequestMethod:@"GET"];
[httpRequest setTimeOutSeconds:60];
[httpRequest startSynchronous];
NSError *error=httpRequest.error;
if(error==nil)
{
NSData *data=httpRequest.responseData;
UIImage *image=[UIImage imageWithData:data];
self.image=image;
}else
{
NSLog(@"請求網絡錯誤");
}
第2、異步請求:async
用delegate實現:url
-(void)asynchronous:(NSURL*)url
{
ASIHTTPRequest *httpRequest=[ASIHTTPRequest requestWithURL:url];
[httpRequest setRequestMethod:@"GET"];
[httpRequest setTimeOutSeconds:60];
httpRequest.delegate=self;
[httpRequest startAsynchronous];
}
#pragma mark - ASIHTTPRequest delegate
- (void)requestFinished:(ASIHTTPRequest *)request
{
UIImage *image=[UIImage imageWithData:request.responseData];
self.image=image;
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
NSError *error=request.error;
NSLog(@"請求出錯:%@",error);
}
用block實現:spa
ASIHTTPRequest *httpRequest=[ASIHTTPRequest requestWithURL:url];
[httpRequest setRequestMethod:@"GET"];
[httpRequest setTimeOutSeconds:60];
//httpRequest.delegate=self;
[httpRequest setCompletionBlock:^{
UIImage *image=[UIImage imageWithData:httpRequest.responseData];
self.image=image;
}];
[httpRequest setFailedBlock:^{
NSError *error=httpRequest.error;
NSLog(@"請求出錯:%@",error);
}];
[httpRequest startAsynchronous];
Block 回調:操作系統
- (void)setStartedBlock:(ASIBasicBlock)aStartedBlock;
- (void)setHeadersReceivedBlock:(ASIHeadersBlock)aReceivedBlock;
- (void)setCompletionBlock:(ASIBasicBlock)aCompletionBlock;
- (void)setFailedBlock:(ASIBasicBlock)aFailedBlock;
- (void)setBytesReceivedBlock:(ASIProgressBlock)aBytesReceivedBlock;
- (void)setBytesSentBlock:(ASIProgressBlock)aBytesSentBlock;
- (void)setDownloadSizeIncrementedBlock:(ASISizeBlock) aDownloadSizeIncrementedBlock;
- (void)setUploadSizeIncrementedBlock:(ASISizeBlock) anUploadSizeIncrementedBlock;
- (void)setDataReceivedBlock:(ASIDataBlock)aReceivedBlock;
第4、緩存策略代理
NSString *cathPath=[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];code
ASIDownloadCache *cache=[[ASIDownloadCachealloc]init];orm
[cache setStoragePath:cathPath];
cache.defaultCachePolicy=ASIOnlyLoadIfNotCachedCachePolicy;
//持久緩存,一直保存在本地
httpRequest.cacheStoragePolicy = ASICachePermanentlyCacheStoragePolicy;
httpRequest.downloadCache=cache;
[httpRequest startAsynchronous];
//監聽數據的來源
if (httpRequest.didUseCachedResponse) {
NSLog(@"data is from cache");
}else
{
NSLog(@"data is form net");
}