开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜