Objective-C& ASIHTTPRequest 返回值
我在 Objective-C Mac 应用程序中使用 ASIHTTPRequest。我正在创建一个访问 Web 服务的公共 API(通过 ASIHTTPRequest)的类,我们将其称为 PublicAPI
。我想要做的是编写直接从 Web 服务返回数据的方法,就像这样......
publicAPI = [[PublicAPI alloc] initWithAccountInfo:email:[self email] password:[self password]];
NSArray *theData = [publicAPI getData];
因此,getData
需要启动 ASIHTTPRequestAND 返回响应从服务器。问题是我想使用 ASIHTTPRequest 的 startAsynchronous 选项进行 ASIHTTPRequest 调用,该选项将服务器的响应委托给 requestFinished 方法。
如何使用requestFinished
的结果作为getData
方法的返回值?
感谢您的建议!
I am using ASIHTTPRequest in an Objective-C Mac application. I am creating a class that accesses a web service's public API (via ASIHTTPRequest), let's call it PublicAPI
. What I am wanting to do is write methods that directly return data from the web service, something like this...
publicAPI = [[PublicAPI alloc] initWithAccountInfo:email:[self email] password:[self password]];
NSArray *theData = [publicAPI getData];
So, getData
needs to initiate the ASIHTTPRequest AND return the response from the server. The problem is that I want to make the ASIHTTPRequest calls with ASIHTTPRequest's startAsynchronous
option, which delegates the server's response to a requestFinished
method.
How can I use the result of requestFinished
as the return value of the getData
method?
Thanks for your advice!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的方法需要
getData
等待响应返回后再返回,这将使连接同步。这确实没有道理。ASIHTTPRequest(以及 NSURLConnection)已经实现的委托模式是这里最好的方法。
如果您只需要建立同步连接进行测试,NSURLConnection 有一个类方法:
Your approach would require that
getData
wait until the response came back before returning which would make the connection synchronous. This does not really make sense.The delegate pattern that is already implemented by ASIHTTPRequest (and NSURLConnection for that matter) is the best approach here.
If you just need to make a synchronous connection for testing, NSURLConnection has a class method for that:
让你的
[公共API获取数据]
实际上是 ASIHTTPRequest 的子类。它将接收 ASI 委托的回调(成功、失败),并将处理(JSON、XML、CoreData 等)您传入的数据。
在处理数据后,您可以使用任何类型的通知将 NSArray 数据返回到您想要的位置。
如果您为每个后端的 API 调用进行子类化,并使用一个通用系统来处理每个 API 调用,则可以使与后端的通信变得轻松愉快。
Make your
[publicAPI getData]
actually be a subclass of ASIHTTPRequest. That will receive the ASI delegate's callbacks (success,fail) and that will process (JSON, XML, CoreData, whatever) your incoming data.
You could use any type of notification, after the data is processed, to get the NSArray data back to where you want it.
If you subclass for each of your backend's API calls, with a common system of processing each for your API, you can make communicating with your backend nice and easy.