How can I get NSURLResponse body?

46,723

Why do you cancel the connection? After all, 404 can have content body as well. Just don't cancel it, and let the program call the next delegate NSURLConnection method. When the data [the content body] is sent - (void)connection:(NSURLConnection *) didReceiveData:(NSData *) is called, you need to retrieve the data there. Read corresponding part in the docs:

The response from a server to a request can be viewed as two parts: metadata describing the contents and the URL content data. The metadata that is common to most protocols is encapsulated by the NSURLResponse class and consists of the MIME type, expected content length, text encoding (where applicable), and the URL that provided the response.

The NSURLConnection and NSURLDownload classes provide the interface to make a connection specified by an NSURLRequest object and download the contents. An NSURLConnection object provides data to the delegate as it is received from the originating source, whereas an NSURLDownload object writes the request data directly to disk. Both classes provide extensive delegate support for responding to redirects, authentication challenges, and error conditions.

As for an example delegate implementation:

-   (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData{
    NSLog(@"String sent from server %@",[[NSString alloc] initWithData:theData encoding:NSUTF8StringEncoding]);

}
Share:
46,723
Admin
Author by

Admin

Updated on December 19, 2020

Comments

  • Admin
    Admin over 3 years

    I'm writing an application that connect with a server using NSURLConnection.

    In the delegate method didreceiveresponse, if the status code is 404, I cancel the connection and I would like to show a message with a custom error that is generated in the server.

    The problem is that from response object, I only can get statuscode, headers, mimetype, etc. but no body.

    How do I get the body message from NSURLResponse?