返回使用AsiHTTPRequest的方法的值

我有一个使用AsiHTTPRequest的类。 我想做一个像这样的方法:

-(NSData*)downloadImageFrom: (NSString*)urlString; { // Set reponse data to nil for this request in the dictionary NSMutableData *responseData = [[NSMutableData alloc] init]; [responseDataForUrl setValue:responseData forKey:urlString]; // Make the request NSURL *url = [NSURL URLWithString:urlString]; ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; [responseDataForUrl setValue:responseData forKey:[request url]]; [request setDelegate:self]; [request startAsynchronous]; // Wait until request is finished (???? Polling ?????) // while(responsedata = nil) { // do nothing // } BAD SOLUTION return responseData; } 

之后。 当responseData准备就绪时调用委托方法。 有没有更好的解决scheme继续,比在variablesresponseData轮询?

您的代表不必是一个单独的类。

 - (void)someMethod:(NSUrl *)url { ASIHTTPRequest *req = [ASIHTTPRequest requestWithUrl:url]; [req setDelegate:self]; //configure the request [req startAsynchronous]; } - (void)requestDone:(ASIHTTPRequest *)request { NSString *response = [request responseString]; //do whatever with the response } 

所以你的方法someMethod:触发请求并返回void。 当请求完成时,你的ASIHTTPRequest在它的委托上触发requestDone:方法,这是同一个对象 。 在这种方法中,你可以做任何事情 – 设置一个ivar或一个命名的属性,处理传入的数据并填充一个UITableVew,无论如何。

请注意,ASIHTTPRequest现在已被弃用,其作者build议使用别的东西。 AFNetworking似乎是一个stream行的select,但我最近还没有开始一个新的项目,所以我还没有select一个自己。

我使用ASIHttpRequest来处理大部分的Web服务调用,但是对于您的情况(获取图像数据asynchronous),我使用GCD块。 我有一个叫做WebImageOperations的类,在这个类中我有一个类方法:

WebImageOperations.h:

 + (void)processImageDataWithURLString:(NSString *)urlString andBlock:(void (^)(NSData *imageData))processImage; 

WebImageOperations.m:

 + (void)processImageDataWithURLString:(NSString *)urlString andBlock:(void (^)(NSData *imageData))processImage { NSURL *url = [NSURL URLWithString:urlString]; dispatch_queue_t callerQueue = dispatch_get_current_queue(); dispatch_queue_t downloadQueue = dispatch_queue_create("com.achcentral.processimagedataqueue", NULL); dispatch_async(downloadQueue, ^{ NSData * imageData = [NSData dataWithContentsOfURL:url]; dispatch_async(callerQueue, ^{ processImage(imageData); }); }); dispatch_release(downloadQueue); } 

然后调用它,使用这个:

 [WebImageOperations processImageDataWithURLString:@"MyURLForPicture" andBlock:^(NSData *imageData) { if (self.view.window) { UIImage *image = [UIImage imageWithData:imageData]; self.myImageView.image = image; } }]; 

你绝对不应该做投票!

您设置为self的ASIHHTPRequest的委托将调用一个方法(请参阅ASIHTTPRequest文档以获取该委托方法的详细信息),以在完成时通知您。 在那个委托方法中,调用你想要做的其他代码。 不要担心返回的图像 – 这都是asynchronous的。