Re: Why does NSURLSession return NSURLResponse instead of NSHTTPURLResponse
Re: Why does NSURLSession return NSURLResponse instead of NSHTTPURLResponse
- Subject: Re: Why does NSURLSession return NSURLResponse instead of NSHTTPURLResponse
- From: "Quinn \"The Eskimo!\"" <email@hidden>
- Date: Wed, 18 Oct 2017 08:53:50 +0100
On 17 Oct 2017, at 23:05, Sebastien Boisvert <email@hidden>
wrote:
> What would make it a NSURLResponse (when a valid response is returned)
> instead of a NSHTTPURLResponse?
As Jens said, it’s correct to rely on the response being an NSHTTPURLResponse
when the request’s URL is `http://` or `https://`. I’ve been working with
NSURLSession (and before that NSURLConnection) for about as long as Jens has,
and it’s always worked that way. I work in Swift mostly these days, and my
completion handlers tend to include this:
let response = response as! HTTPURLResponse
… test response.statusCode …
which is going to hard crash if this fails.
The only situations I know of where you’ll get `NSURLSession` are:
* You pass in a request whose URL uses some other scheme, for example, `ftp://`
* You’ve implemented a custom NSURLProtocol subclass for HTTP-sytle requests
and create the wrong response [1]
* * *
Some questions / suggestions for moving this forward:
* Do you have any NSURLProtocol subclasses in play here?
* Are you sure that the crash is because you got an NSURLResponse? If you have
some other problem you could get a similar looking crash. In Objective-C I
typically write this:
NSHTTPURLResponse * httpResponse = (NSHTTPURLResponse *) response;
assert([httpResponse isKindOfClass:[NSHTTPURLResponse class]);
so I’d trap this error immediately.
* You could add a trap like this:
assert([response.URL.scheme isEqual:@"http"]);
* You might want to enable a CFNetwork diagnostic log, per QA1887. If you can
reproduce the crash with that logging enabled, it might reveal something
interesting.
<https://developer.apple.com/library/content/qa/qa1887/_index.html>
Share and Enjoy
--
Quinn "The Eskimo!" <http://www.apple.com/developer/>
Apple Developer Relations, Developer Technical Support, Core OS/Hardware
[1] Back in the day this was a tricky because NSHTTPURLResponse has no public
initialisers but that was fixed OS X 10.7 / iOS 5.0.
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Macnetworkprog mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden