views:

352

answers:

1

Dumb question, but how do I check if a file exists on a web site. I am using NSURLConnection with my NSURLRequest and an NSMutableData object to store what comes back in the didReceiveData delegate method. In the connectionDidFinishingLoading method I then save the NSMutableData object to the file system. All good. Except if the file does not exist at the website, my code still runs, gets data and saves a file.

How can I check the file is there before I make download request?

Regards

Dave

+1  A: 

Implement connection:didReceiveResponse:, which will be called before connection:didReceiveData:.

The response should be an NSHTTPURLResponse object — suppose you're issuing an HTTP request. You can therefore check [response statusCode] == 404 to determine if the file exists or not.

See also http://stackoverflow.com/questions/1404366/check-if-nsurl-returns-404.

KennyTM
That is great thanks Kenny. Do you know if I can/should implement the following in my didReceiveResponse? NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response; if ([httpResponse statusCode] == 404) // File does not exist { [connection cancel]; }
Magic Bullet Dave
Sorry should have added, that all works a treat. Just wondering if it is recommended to cancel the connection like that?
Magic Bullet Dave