我们的要求包括检查对Web服务器上特定文件的Internet访问。每隔 n 分钟检查此文件。 NSURLRequests 从不调用connection:didFailWithError是否存在互联网连接。并且HTTP状态始终为200. Apple的可访问性仅适用于域,而不适用于文件 - 因此它不符合要求。如何可靠地发现我是否可以每隔 n 分钟到达此文件?为什么http状态代码真的不是http状态代码?
似乎回答这个问题的其他stackoverflow问题不起作用:
1. How could connectionDidFinishLoading: run if no file is found on server?
2. Testing use of NSURLConnection with HTTP response error statuses
我尝试使用另一个带有完成块的队列,但这也无效。
-(void) updateConnectionStatus
{
NSURL *url = [NSURL URLWithString:(NSString*)[appValues getValueForSettingsKey:@"company.project.test.pingURL"]];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
//NSOperationQueue *queue = [[NSOperationQueue alloc] init];
//__block __typeof__(self) _self = self;
connection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
/*
[NSURLConnection
sendAsynchronousRequest:urlRequest queue:queue
completionHandler:^(NSURLResponse *response,
NSData *data,
NSError *error) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
int code = [httpResponse statusCode]; // ALWAYS 200 no matter what
NSString *pingFile = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@",error); // NEVER has an error
//This doesn't even work because it remembers FOREVER the value once it gets it.
if ([@"Ping!" isEqualToString:pingFile])
{
dispatch_async(dispatch_get_main_queue(), ^{
[_self companyConnection:YES];
});
} else {
dispatch_async(dispatch_get_main_queue(), ^{
[_self companyConnection:NO];
});
}
}];
*/
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"ERROR: %@", error); // Never get here
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSHTTPURLResponse *aResponse = (NSHTTPURLResponse*)response;
NSLog(@"received a response: %ld",(long)[aResponse statusCode] );
if ([response respondsToSelector:@selector(statusCode)])
{
int statusCode = [((NSHTTPURLResponse *)response) statusCode];
// statusCode is always 200
if (statusCode >= 400)
{
[companyConnection cancel]; // stop connecting; no more delegate messages
NSDictionary *errorInfo
= [NSDictionary dictionaryWithObject:[NSString stringWithFormat:
NSLocalizedString(@"Server returned status code %d",@""),
statusCode]
forKey:NSLocalizedDescriptionKey];
}
}
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(@"received data");
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"Finished");
}
答案 0 :(得分:0)
尝试在构造NSURLRequest对象时将cachePolicy设置为NSURLRequestReloadIgnoringCacheData
答案 1 :(得分:0)
感谢Wain和Rob让我走上了正确的道路。保持缓存清晰的一种方法是将此方法添加到NSURLConnectionDelegate:
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse
{
return nil;
}