在iOS中检测Web服务器上是否存在文件(HTML)的正确方法是什么?使用以下方法检测myfile.html的存在总是返回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");
}
我相信它正在返回与HTTP服务器的连接成功,而不是检查文件myfile.html是否实际存在。
答案 0 :(得分:5)
您需要使用连接:didReceiveResponse委托方法来检查http响应代码。以下内容将检查以确保您收到200响应,具体取决于您的服务器,如果该文件不存在,我希望状态代码为404.
- (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");
}
}