특정 URL에 파일이 있는지 확인하는 방법은 무엇입니까?
-
19-09-2019 - |
문제
웹 사이트에 파일이 존재하는지 어떻게 확인합니까? 나는 사용 중입니다 NSURLConnection
내 NSURLRequest
그리고 NSMutableData
객체로 돌아 오는 것을 저장합니다 didReceiveData:
대표 방법. 에서 connectionDidFinishingLoading:
방법 I 다음을 저장합니다 NSMutableData
파일 시스템에 반대합니다. 문제 없다. 제외 : 파일이 웹 사이트에 존재하지 않으면 내 코드가 여전히 실행되고 데이터를 가져오고 파일을 저장합니다.
다운로드 요청을하기 전에 파일이 있는지 확인하려면 어떻게해야합니까?
해결책
구현하다 connection:didReceiveResponse:
, 이전에 호출됩니다 connection:didReceiveData:
.
응답은 an이어야합니다 NSHTTPURLResponse
개체 - HTTP 요청을 발행한다고 가정 해 봅시다. 따라서 확인할 수 있습니다 [response statusCode] == 404
파일이 존재하는지 여부를 결정합니다.
또한보십시오 NSURL이 404를 반환하는지 확인하십시오.
다른 팁
1. 번들에 파일
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. 디렉토리에서 파일
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. 웹에서 파일
NSString *urlString=@"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");
}
제휴하지 않습니다 StackOverflow