首页 > 代码库 > ios中的ASIHTTPRequest的同步请求和异步请求

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 = http://www.mamicode.com/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 = http://www.mamicode.com/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 = [ASIHTTPRequestrequestWithURL:url];

    [request setRequestMethod:@"GET"];

    [request setTimeOutSeconds:60];

    

    //设置网络请求完成后的block此时不需要delegate

    

    [request setCompletionBlock:^{

        NSData *data = http://www.mamicode.com/request.responseData;

        self.image = [UIImageimageWithData:data];

    }];

    //设置请求失败调用的block

    [requestsetFailedBlock:^{

        NSError *error = [requesterror];

        NSLog(@"网络请求失败%@",error);


    }];

    [request startAsynchronous];

    

}