views:

33

answers:

2

I need to check if a file exists on my server without using cache. The methods I have used are all returning a 200, even if the file does not exist, so I can only assume there is a cache problem, or theres a problem with my code.

Heres my code: for arguments sake..the URL is changed in this example, but the url is correct in my code.

NSString *auth = [NSString stringWithFormat:@"http://www.mywebsite.com/%@.txt",[self aString]];
NSURL *authURL = [NSURL URLWithString:auth];

NSURLRequest* request = [NSURLRequest requestWithURL:authURL 
                                         cachePolicy:NSURLRequestReloadIgnoringCacheData
                                     timeoutInterval:5.0];
NSURLConnection *conn = [NSURLConnection connectionWithRequest:request
                                                      delegate:self];

NSHTTPURLResponse* response = nil;
NSError* error = nil;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(@"statusCode = %d", [response statusCode]);

if ([response statusCode] == 404)
    NSLog(@"MISSING");
else
    NSLog(@"EXISTS");

the response is always 200, even if I rename the file on the server.

+1  A: 

There are a couple of potential problems with your code. First, when you create conn using connectionWithRequest:delegate: you are starting an asynchronous request. The response would be received in the delegate's (self in your case) connection:didReceiveResponse: method. Are you trying to do the request asynchronously? From the rest of your code though, it looks like you are actually trying to do a synchronous request. That's what sendSynchronousRequest:returningResponse:error: is for. If that's what you intend, then you don't need the earlier call to create a connection.

Assuming thats the case, you need to capture and check the value returned from calling sendSynchronousRequest:returningResponse:error:. It will return nil if the connection failed, which is what I suspect is happening. You can then look at the error returned to figure out what is going on. Try something like:

NSData * result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

if (result != nil) {
   NSLog(@"statusCode = %d", [response statusCode]);

   if ([response statusCode] == 404)
    NSLog(@"MISSING");
   else
       NSLog(@"EXISTS");
} else {
  NSLog(@"%@", error);
}
Jason Jenkins
It was actually my server. I use custom Error docs, so I just disabled the 404, and voila!
AWright4911
+1  A: 

Is it possible it's caching on the server side? If so you could try NSURLRequestReloadIgnoringLocalAndRemoteCacheData instead of NSURLRequestReloadIgnoringCacheData.

amrox