简体   繁体   English

NSURLConnection并处理响应代码和响应数据

[英]NSURLConnection and handling response code and response data

I have an odd edge case right now in that a response code from an NSURLConnection delegate method: 我现在有一个奇怪的情况,那就是来自NSURLConnection委托方法的响应代码:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;

Is triggered before the subsequent delegate method: 在后续委托方法之前触发:

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;

My code could certainly use improvement as right now it checks for the HTTP Response Code from the above, then calls on some method to take action. 我的代码肯定可以使用改进,因为它现在从上面检查HTTP响应代码,然后调用某种方法来采取措施。 Unfortunately at that point, the data is not yet available. 不幸的是,当时还没有可用的数据。

What are some elegant solutions for coupling the response and the responseData in a fashion that my classes method is not triggered until the response and the responseData are 200 + not nil . 有什么精美的解决方案可以使responseresponseData耦合,以至于我的类方法直到response responseData为200 +不为nil时才被触发。 Do I need to set both of them as class instance variables? 我是否需要将它们都设置为类实例变量? Seems like a poor man's solution. 似乎是一个穷人的解决方案。

Response before data is the correct order. 数据之前的响应是正确的顺序。 In fact, you should be clearing any data in this method (in case you receive multiple responses through redirections and any intervening data is made obsolete). 实际上,您应该使用此方法清除所有数据(以防您通过重定向收到多个响应并且所有中间数据都已过时)。

You receive a connection:didReceiveResponse: message to tell you that a reply header has been received but this occurs before any body content. 您收到一条connection:didReceiveResponse:消息,告诉您已收到回复标头,但这发生任何正文内容之前

If you need access to all elements of the reply, you should simply store the response and the data as they come in and only handle them in connectionDidFinishLoading: (or if your data is long, you can handle incrementally in connection:didReceiveData:). 如果您需要访问答复的所有元素,则应简单地存储响应和传入的数据,仅在connectionDidFinishLoading:中处理它们(或者,如果数据很长,则可以在connection:didReceiveData:中进行增量处理)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM