ios中的ASIHTTPRequest的同步请求和异步请求
1、首先加入ASI开源库
2、
WebImageView.h
#import <UIKit/UIKit.h>
#import "ASIHTTPRequest.h"
@interface WebImageView :UIImageView<ASIHTTPRequestDelegate>
- (void)setImageURL:(NSURL *)url;
@end
WebImageView.m
#import "WebImageView.h"
#import"ASIHTTPRequest.h"
@implementation WebImageView
- (id)initWithFrame:(CGRect)frame
{
self = [superinitWithFrame:frame];
if (self) {
// Initialization code
}
returnself;
}
- (void)setImageURL:(NSURL *)url{
//同步请求
//[self synchronous:url];
//异步请求
[selfasynchronous:url];
}
//同步请求
- (void)synchronous:(NSURL *)url{
ASIHTTPRequest *request = [ASIHTTPRequestrequestWithURL:url];
[request setRequestMethod:@"GET"];
[request setTimeOutSeconds:60];
//设置请求头
//[request setRequestHeaders:<#(NSMutableDictionary *)#>];
//设置cookie
//[request setRequestCookies:<#(NSMutableArray *)#>];
//发送同步请求
[request startSynchronous];
NSError *error = [requesterror];
if (error ==nil) {
//获取请求下来的数据
NSData *data = request.responseData;
UIImage *image = [UIImageimageWithData:data];
self.image = image;
}else{
NSLog(@"网络请求失败%@",error);
}
}
//异步请求
-(void)asynchronous:(NSURL *)url{
ASIHTTPRequest *request = [ASIHTTPRequestrequestWithURL:url];
[request setRequestMethod:@"GET"];
[request setTimeOutSeconds:60];
request.delegate =self;
[request startAsynchronous];
}
#pragma mark ASIHTTPRequest delegate------异步请求的协议方法的实现---------
//请求数据完成
- (void)requestFinished:(ASIHTTPRequest *)request{
NSData *data = request.responseData;
self.image = [UIImageimageWithData:data];
}
//请求失败
- (void)requestFailed:(ASIHTTPRequest *)request{
NSError *error = [requesterror];
NSLog(@"网络请求失败%@",error);
}
@end
3、运用Block方式进行网络异步请求,此时不需要实现delegate
//异步请求
-(void)asynchronous:(NSURL *)url{
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setRequestMethod:@"GET"];
[request setTimeOutSeconds:60];
//设置网络请求完成后的block此时不需要delegate
[request setCompletionBlock:^{
NSData *data = request.responseData;
self.image = [UIImage imageWithData:data];
}];
//设置请求失败调用的block
[request setFailedBlock:^{
NSError *error = [request error];
NSLog(@"网络请求失败%@",error);
}];
[request startAsynchronous];
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。