Cocoa Touch: How to detect a missing file on the download server
开发者_开发技巧My iOS app downloads document files from a server using the NSURLConnection class. I use it asynchronously.
It can happen that a document is missing from the server (configuration error). I expected NSURLConnection to call my delegate error method:
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
But it doesn't. Instead, it happily downloads the HTML error 404 web page returned by the server. The only workaround I found was to check the NSURLResponse MIMEtype property and fail myself when it is text/html. It works fine, but I don't like it because it precludes me from supporting html documents at a later date.
How can I check whether a requested URL is indeed present on the server?
Thanks
In the - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response delegate method you can ask the response for it's error code.
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
if (httpResponse.statusCode == 404) {
...
//etc
When you receive the response (in -connection:didReceiveResponse:), you get to query the response. Because you're using HTTP, it will be a kind of NSHTTPURLResponse, though you may want to test for that. Anyway, it will tell you a -statusCode, which might be 200, 404 or something else.
加载中,请稍侯......
精彩评论