NSURLConnection - Get HTTP status code on request failure

294 views Asked by At

Is there any way I can get HTTP status code after NSURLConnection has failed to request? According to the documentation, I can get the HTTP status code from -connection:didReceiveResponse:. However, in case the request fails, only -connection:didFailedWithError: is called, and by far I haven't found any method to get status code inside this method.

p/s: I'm working on a VERY old, complicated project, and it's very error-prone, so I cannot use AFNetworking or NSURLSession.

1

There are 1 answers

5
ekscrypto On

As mentioned in the Apple docs for NSURLConnectionDataDelegate Protocol the connection:didReceiveResponse: is called only when sufficient data has been received to create the NSURLResponse object.

While the NSURLResponse object may not be available until later, it is possible for a connection to receive partial data by using the connection:didReceiveData: method. Note that this seems to exclude the HTTP headers and only contain the "data" component of the response. There may be a way to trigger the didReceiveResponse: early if the server knows ahead of time how much data will be transmitted although I am no familiar enough with this to confirm.

Be aware that the response data typically comes in blocks of approximately 1KiB of data each, depending on various network settings such as MTU and how often the server "flush" its output pipe.

Good luck!