使用AsiHTTPRequest的方法的返回值 [英] Return Value of method using AsiHTTPRequest

查看:151
本文介绍了使用AsiHTTPRequest的方法的返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a class that uses AsiHTTPRequest. I want to make a method like this:

-(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中轮询?

After that. A delegate method is called when the responseData is ready. Is there a better solution to continue, than doing polling in the variable responseData?

推荐答案

您的委托不必是单独类。

Your delegate doesn't have to be a separate class.

- (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
}

c $ c> someMethod:触发请求并返回void。当请求完成后,您的ASIHTTPRequest在其委托上触发 requestDone:方法,这是同一个对象 。在该方法中,您可以执行任何操作 - 设置一个ivar或一个命名属性,处理传入数据并填充UITableVew。

So your method someMethod: fires the request and returns void. When the request is finished, your ASIHTTPRequest fires the requestDone: method on its delegate, which is this same object. In that method, you do whatever--set an ivar or a named property, process incoming data and populate a UITableVew, whatever.

请注意,ASIHTTPRequest现已弃用,它的作者建议使用别的东西。 AFNetworking似乎是一个流行的选择,但我最近没有开始一个新项目,所以我还没有自己选择一个。

Note that ASIHTTPRequest is now deprecated, and its author recommends using something else instead. AFNetworking seems a popular choice, but I haven't started a new project recently so I haven't picked one yet myself.

这篇关于使用AsiHTTPRequest的方法的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆