문제

인앱 구매가있는 응용 프로그램이 있는데, 사용자가 무언가를 구매할 때 앱의 문서 폴더에 하나의 html 파일을 다운로드하는 응용 프로그램이 있습니다.

이제이 HTML 파일이 있는지 확인해야하므로 True이라면이 HTML 파일을로드하면 기본 HTML 페이지를로드하십시오.

어떻게 할 수 있습니까? 와 함께 NSFileManager 나는 밖에 나갈 수 없다 mainBundle..

도움이 되었습니까?

해결책

스위프트 3 :

let documentsURL = try! FileManager().url(for: .documentDirectory,
                                          in: .userDomainMask,
                                          appropriateFor: nil,
                                          create: true)

... 문서 디렉토리의 파일 URL을 제공합니다. 다음은 foo.html이라는 파일이 있는지 확인합니다.

let fooURL = documentsURL.appendingPathComponent("foo.html")
let fileExists = FileManager().fileExists(atPath: fooURL.path)

대상 C :

NSString* documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];

NSString* foofile = [documentsPath stringByAppendingPathComponent:@"foo.html"];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:foofile];

다른 팁

Apple은 file -existatpath : method에 의존하는 것을 권장합니다. 파일이 존재하지 않으면 파일을 열고 오류를 처리하는 것이 좋습니다.

NSFILEMANAGER 클래스 참조

참고 : 파일 시스템의 현재 상태 또는 파일 시스템의 특정 파일을 기반으로 동작을 술어를 시도하는 것은 권장되지 않습니다. 그렇게하면 이상한 행동이나 인종 조건을 유발할 수 있습니다. 작업을 시도하거나 디렉토리 생성과 같은 작업을 시도하고 오류를 확인하고 오류를 미리 파일을 성공적으로 파악하는 것보다 오류를 확인하고 오류를 우아하게 처리하는 것이 훨씬 좋습니다. 파일 시스템 레이스 조건에 대한 자세한 내용은 보안 코딩 안내서의 "레이스 조건 및 보안 파일 작업"을 참조하십시오.

원천: Apple 개발자 API 참조

보안 코딩 안내서에서.

이를 방지하기 위해 프로그램은 종종 특정 이름이있는 임시 파일이 대상 디렉토리에 아직 존재하지 않는지 확인합니다. 그러한 파일이 존재하는 경우 응용 프로그램은 충돌을 피하기 위해 임시 파일의 새 이름을 삭제하거나 새 이름을 선택합니다. 파일이 존재하지 않으면 응용 프로그램은 쓰기를 위해 파일을 열는 시스템 루틴이 없으면 새 파일을 자동으로 생성하기 때문에 응용 프로그램은 작성을 위해 파일을 엽니 다. 공격자는 적절한 이름으로 새 임시 파일을 생성하는 프로그램을 지속적으로 실행함으로써 (약간의 지속성과 운이 좋으면) 응용 프로그램이 임시 파일이 존재하지 않도록 확인했을 때 간격의 파일을 만들 수 있습니다. 그리고 그것이 글을 쓸 때. 그런 다음 응용 프로그램은 공격자의 파일을 열고 씁니다 (시스템 루틴은 기존 파일이있는 경우 기존 파일을 열고 기존 파일이없는 경우에만 새 파일을 만듭니다). 공격자의 파일은 응용 프로그램의 임시 파일과 다른 액세스 권한을 가질 수 있으므로 공격자는 내용을 읽을 수 있습니다. 또는 공격자에게 파일이 이미 열려있을 수 있습니다. 공격자는 파일을 다른 파일 (공격자 소유 또는 기존 시스템 파일)으로 하드 링크 또는 상징적 링크로 바꿀 수 있습니다. 예를 들어, 공격자는 파일을 시스템 비밀번호 파일에 대한 기호 링크로 바꿀 수 있으므로 공격 후 시스템 관리자를 포함한 어느 누구도 로그인 할 수없는 시점까지 시스템 암호가 손상되었습니다.

파일 시스템을 다르게 설정하거나 파일 시스템을 설정 한 다음 문서 폴더에 파일이 존재하는지 확인하는 다른 방법을 찾는 경우 다른 예제가 있습니다. 또한 동적 검사를 보여줍니다

for (int i = 0; i < numberHere; ++i){
    NSFileManager* fileMgr = [NSFileManager defaultManager];
    NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSString* imageName = [NSString stringWithFormat:@"image-%@.png", i];
    NSString* currentFile = [documentsDirectory stringByAppendingPathComponent:imageName];
    BOOL fileExists = [fileMgr fileExistsAtPath:currentFile];
    if (fileExists == NO){
        cout << "DOESNT Exist!" << endl;
    } else {
        cout << "DOES Exist!" << endl;
    }
}

스위프트 2.0

파일이 Swift를 사용하여 존재하는지 확인하는 방법입니다.

func isFileExistsInDirectory() -> Bool {
    let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
    let documentsDirectory: AnyObject = paths[0]
    let dataPath = documentsDirectory.stringByAppendingPathComponent("/YourFileName")

    return NSFileManager.defaultManager().fileExistsAtPath(dataPath)
}

파일이 문서/catchimage 경로에 존재하는지 확인하십시오.

NSString *stringPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString *tempName = [NSString stringWithFormat:@"%@/catchimage/%@.png",stringPath,@"file name"];
NSLog(@"%@",temName);
if([[NSFileManager defaultManager] fileExistsAtPath:temName]){
    // ur code here
} else {
    // ur code here** 
}
NSArray *directoryPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *imagePath =  [directoryPath objectAtIndex:0];
//If you have superate folder
imagePath= [imagePath stringByAppendingPathComponent:@"ImagesFolder"];//Get docs dir path with folder name
_imageName = [_imageName stringByAppendingString:@".jpg"];//Assign image name
imagePath= [imagePath stringByAppendingPathComponent:_imageName];
NSLog(@"%@", imagePath);

//Method 1:
BOOL file = [[NSFileManager defaultManager] fileExistsAtPath: imagePath];
if (file == NO){
    NSLog("File not exist");
} else {
    NSLog("File exist");
}

//Method 2:
NSData *data = [NSData dataWithContentsOfFile:imagePath];
UIImage *image = [UIImage imageWithData:data];
if (!(image == nil)) {//Check image exist or not
    cell.photoImageView.image = image;//Display image
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top