1.同步请求 ASIHTTPRequest*request= [ASIHTTPRequest requestWithURL:url]; [request setRequestMethod:@"GET"]; [request setTimeOutSeconds:50]; [request startSynchronous]; NSError *error=request.error; if (error==nil) { NSData *data= request.responseData; UIImage*image= [UIImage imageWithData:data]; self.image=image; }else{ NSLog(@"请求出错"); }
2.异步请求 -(void)setImageURL:(NSURL *)url{ ASIHTTPRequest*request= [ASIHTTPRequest requestWithURL:url]; [request setRequestMethod:@"GET"]; [request setTimeOutSeconds:50]; request.delegate=self;//这个是与同步请求不一样的地方 [request startAsynchronous]; } - (void)requestFinished:(ASIHTTPRequest *)request{ NSData*imagedata= request.responseData; UIImage *image= [UIImage imageWithData:imagedata]; self.image=image; //监听还是主线程,所以不用跳 } - (void)requestFailed:(ASIHTTPRequest *)request{ NSLog(@"%@失败",request.error); }
-(void)setImageURL:(NSURL *)url{ ASIHTTPRequest*request= [ASIHTTPRequest requestWithURL:url]; [request setRequestMethod:@"GET"]; [request setTimeOutSeconds:50]; [request setCompletionBlock:^{ NSData*imagedata= request.responseData; UIImage *image= [UIImage imageWithData:imagedata]; self.image=image; }]; [request startAsynchronous]; } 这个异步请求就没有设置代理,其代理方法用一个block代替了,每个代理方法都对应一个block