Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is a NSURLResponse not a NSHTTPURLResponse?

I've seen a lot of code, including Apple's SimpleURLConnections sample, that simply cast any NSURLResponse to a NSHTTPURLResponse. If it is always a NSHTTPURLResponse why do the NSURLConnections not return NSHTTPURLResponse?

I'm worried that if I simply downcast the response, I'm introducing buggy code.

For instance, is it OK to do this without checking isKindOfClass?

- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse
{
 NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)redirectResponse;
 // do stuff
}
like image 986
CornPuff Avatar asked Sep 13 '11 04:09

CornPuff


2 Answers

It is ok if you are sure that your connection runs via HTTP protocol:

An NSHTTPURLResponse object represents a response to an HTTP URL load request. It’s a subclass of NSURLResponse that provides methods for accessing information specific to HTTP protocol responses.

If you are connecting via FTP, for example, then casting NSURLResponse to NSHTTPURLResponse will be incorrect.

like image 76
Nekto Avatar answered Oct 06 '22 08:10

Nekto


The safer way to do it is with introspection.

if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
   NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)redirectResponse;
   // do stuff
}
like image 34
mgold Avatar answered Oct 06 '22 07:10

mgold