code

경로 대신 URL에 파일이 있는지 확인하십시오.

codestyles 2020. 11. 30. 08:18
반응형

경로 대신 URL에 파일이 있는지 확인하십시오.


iPhone 시뮬레이터에 미리 채워진 기본 저장소를 설정하기 위해 경로 대신 URL에 파일이 있는지 어떻게 확인할 수 있습니까?

NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Food.sqlite"];
/*
 Set up the store.
 For the sake of illustration, provide a pre-populated default store.
 */
NSFileManager *fileManager = [NSFileManager defaultManager];
// If the expected store doesn't exist, copy the default store.
if (![fileManager fileExistsAtPath:storePath]) {
    NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:@"Food" ofType:@"sqlite"];
    if (defaultStorePath) {
        [fileManager copyItemAtPath:defaultStorePath toPath:storePath error:NULL];
    }
}

최근 버전의 템플릿에서 applicationDocumentsDirectory 메서드가 URL을 반환한다는 것을 읽었으므로 NSURL 개체를 사용하여 파일 경로를 나타내도록 코드를 변경했습니다. 그러나에서 [fileManager fileExistsAtPath:storePath]나는 (분명히 존재하지 않음) fileExistsAtPath같은 것으로 변경해야합니다 fileExistsAtURL.

NSFileManager 클래스 참조를 확인했지만 내 목적에 적합한 작업을 찾지 못했습니다.

힌트 좀주세요.


if (![fileManager fileExistsAtPath:[storeURL path]]) 
...

로부터 문서 :

이 URL 개체에 파일 URL (isFileURL로 결정됨)이 포함 된 경우이 메서드의 반환 값은 NSFileManager 또는 NSPathUtilities의 메서드에 입력하는 데 적합합니다. 경로에 후행 슬래시가 있으면 제거됩니다.


파일 시스템의 경우 URL NSURL자체에는 URL 의 도달 가능성을 확인하는 방법이 있습니다.

NSError *error;
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Food.sqlite"];
if ([storeURL checkResourceIsReachableAndReturnError:&error]) {
  // do something
} else {
  NSLog(@"%@", error);
}

if (![fileManager fileExistsAtPath:[storeURL path]]) 

괜찮아요,하지만 조심하세요 :

..../Documents/1158a3c96ca22c41b8e731b1d1af0e1e?d=mm&s=50

[storeURL path]해당 경로를 제공합니다 (적용 대상 [storeURL lastPathComponent]:

..../Documents/1158a3c96ca22c41b8e731b1d1af0e1e

그러나 당신이 lastPathComponent와 같은 문자열을 사용하면 당신 /var/mobile/Applications/DB92F4DC-49E4-4B4A-8271-6A9DAE6963BC/Documents/1158a3c96ca22c41b8e731b1d1af0e1e?d=mm&s=50에게 줄 것입니다.1158a3c96ca22c41b8e731b1d1af0e1e?d=mm&s=50

URL에서 '?' GET 매개 변수에 사용되지만 문자열과 혼합하면 문제가 발생할 수 있습니다.

참고 URL : https://stackoverflow.com/questions/7878828/check-if-file-exists-at-url-instead-of-path

반응형