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.
There are a couple of potential problems with your code. First, when you create
connusingconnectionWithRequest:delegate:you are starting an asynchronous request. The response would be received in the delegate’s (selfin 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 whatsendSynchronousRequest: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: