2010-01-07 1 views
2

웹 사이트에 파일이 있는지 어떻게 확인합니까? NSURLConnectionNSURLRequestNSMutableData 개체를 사용하여 didReceiveData: 대리자 메서드에 되돌아 오는 것을 저장하고 있습니다. connectionDidFinishingLoading: 메서드에서 나는 NSMutableData 개체를 파일 시스템에 저장합니다. 문제 없다. 예외 : 웹 사이트에 파일이 없으면 코드가 실행되고 데이터를 가져 와서 파일을 저장합니다.특정 URL에 파일이 있는지 확인하는 방법은 무엇입니까?

다운로드 요청을하기 전에 파일이 있는지 어떻게 확인할 수 있습니까?

+0

HTTP에서 'GET'요청 대신. – Cyrille

답변

3

구현 connection:didReceiveResponse:connection:didReceiveData: 전에 호출됩니다.

응답은 NSHTTPURLResponse 개체 여야합니다. HTTP 요청을 내리고 있다고 가정합니다. 따라서 파일이 존재하는지 여부를 확인하려면 [response statusCode] == 404을 검사 할 수 있습니다.

도 참조하십시오. Check if NSURL returns 404. 웹에서 디렉토리

NSString* path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 
path = [path stringByAppendingPathComponent:@"image.png"]; 
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:path]; 
if (fileExists) { 
NSLog(@"file exists"); 
} 
else 
{ 
NSLog(@"file not exists"); 
} 

3.File에 번들

NSString *path = [[NSBundle mainBundle] pathForResource:@"image" ofType:@"png"]; 
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:path]; 
if (fileExists) { 
NSLog(@"file exists"); 
} 
else 
{ 
NSLog(@"file not exists"); 
} 

2.File에서

+0

큰 감사 케니. didReceiveResponse에서 다음을 구현할 수 있는지/알아야합니까? NSHTTPURLResponse * httpResponse = (NSHTTPURLResponse *) 응답; if ([httpResponse statusCode] == 404) // 파일이 없습니다. { [연결 취소]; } –

+0

죄송합니다, 모든 작품을 추가해야합니다. 그냥 그런 연결을 취소하는 것이 좋습니다 궁금해? –

+0

이것은 작동하지 않습니다. 거짓 긍정 (false positive) - 아무 것도 없을 때 파일의 존재를 부정확하게 나타냅니다. – dugla

2

1.File

`HEAD` 동사가 존재 왜
NSString *[email protected]"http://eraser2.heidi.ie/wp-content/plugins/all-in-one-seo-pack-pro/images/default-user-image.png"; 
NSURL *url=[NSURL URLWithString:urlString]; 
NSURLRequest *request=[NSURLRequest requestWithURL:url]; 
NSURLConnection *connection=[NSURLConnection connectionWithRequest:request delegate:self]; 
[connection start]; 

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{ 
NSLog(@"%@",response); 
[connection cancel]; 
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response; 
int code = (int)[httpResponse statusCode]; 
if (code == 200) { 
    NSLog(@"File exists"); 
} 
else if(code == 404) 
{ 
    NSLog(@"File not exist"); 
} 
} 
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{ 
NSLog(@"File not exist"); 
}