How to detect presence of a file on web server

What would be the correct way in iOS of detecting the presence of a file (HTML) on a web server. Using the following to detect the presence of myfile.html always returns true.

NSURL *url = [NSURL URLWithString:@"http://somewebsite.com/myfile.html"];
NSURLRequest *requestObject = [NSURLRequest requestWithURL:url];

NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:requestObject delegate:self];

if (theConnection) {

    NSLog(@"File exists");

} else {

    NSLog(@"File does NOT exist");
}

I believe it is returning that the connection to HTTP server is successful, and not checking if the file myfile.html actually exists.

Answers


you'll need to use the connection:didReceiveResponse delegate method to check the http response code. something like the following will check to make sure you got a 200 response back, depending on your server i'd expect the status code to be 404 if the file doesn't exist.

- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    //make sure we have a 2xx reponse code
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;

    if ([httpResponse statusCode]/100 == 2){
        NSLog(@"file exists");
    } else {
        NSLog(@"file does not exist");
    }
}

Need Your Help

horizontal LinearLayout with 3 TextViews of which the 2nd has to stay centered

android android-layout

this is my first time asking a Question myself, so please be patient :-).

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.