使用AsiHTTPRequest返回方法的值

时间:2012-02-21 12:02:38

标签: iphone ios cocoa 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准备就绪时调用委托方法。有没有比在变量responseData中进行轮询更好的解决方案?

3 个答案:

答案 0 :(得分:1)

我在大多数网络服务调用中使用ASIHttpRequest,但在你的情况下(获取图像数据异步),我使用带有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;
        }
}];

答案 1 :(得分:0)

你绝对不应该做投票!

您设置为self的ASIHHTPRequest的委托将调用方法(请参阅ASIHTTPRequest文档以获取该委托方法的详细信息)以在完成时通知您。在该委托方法中,调用您想要执行的任何其他代码。不要为返回图像而烦恼 - 它们都是异步的。

答案 2 :(得分:0)

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

- (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现已弃用,其作者建议使用其他内容。 AFNetworking似乎是一个受欢迎的选择,但我最近没有开始一个新项目,所以我还没有选择一个。