简体   繁体   中英

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:

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

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:).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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