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");
}