2017-12-12 18 views
0

사용자가 UIImagePickerController과 함께 찍은 사진을 사용자의 문서 디렉토리에 저장합니다. 응용 프로그램이 서버에 이미지를 성공적으로 업로드하면 로컬로 저장된 이미지를 삭제하려고합니다.목표 C - writeToFile은 성공했지만 removeFile은 동일한 파일에 대해 오류를 반환합니다.

나는이 같은 문서 디렉토리에 이미지를 저장 :

/*delete image stored in documents directory from collecting w/o internet connection*/ 
NSFileManager *fileManager = [NSFileManager defaultManager]; 

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory 
NSString *filePath = [documentsPath stringByAppendingPathComponent:collectedLeaf.localImageFilePath]; 
NSError *error; 
BOOL successDeleteLocalImage = [fileManager removeItemAtPath:filePath error:&error]; 
if(successDeleteLocalImage){ 
    NSLog(@"SUCCESS DELETE IMAGE NO ERROR"); 
    collectedLeaf.localImageFilePath = nil; 
}else{ 
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 
} 

성공적인 쓰기/문서 디렉토리의 사진 인쇄 successfully write to file path /var/mobile/Containers/Data/Application/EA08B79A-7484-4568-82CE-079B4055CDA7/Documents/15130563374.png을 저장

/*Save image to documents directory, as opposed to core data for better memory management*/ 
     NSString *myUniqueName = [NSString stringWithFormat:@"%lu.png", (unsigned long)([[NSDate date] timeIntervalSince1970]*10.0)]; 
     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
     NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory 
     NSString *filePath = [documentsPath stringByAppendingPathComponent:myUniqueName]; //Add the file name 

     BOOL successWriteLocalImage = [imageToUpload writeToFile:filePath options:NSDataWritingAtomic error:&error]; 

      if(successWriteLocalImage){ 
       //NSLog(@"no error success writing to file"); 
       NSLog(@"successfully write to file path %@", filePath); 

      }else{ 
       NSLog(@"Unresolved error writing to file %@, %@", [error localizedDescription], [error userInfo]); 
      } 
     /*Save file path of leaf image to core data here*/ 
     collectedLeaf.localImageFilePath = filePath; 

     [context save:&error]; 

그래서 같이 같은 파일을 삭제합니다.

파일 로그

Unresolved error Error Domain=NSCocoaErrorDomain Code=4 "“15130563374.png” couldn’t be removed." UserInfo={NSFilePath=/var/mobile/Containers/Data/Application/EA08B79A-7484-4568-82CE-079B4055CDA7/Documents/var/mobile/Containers/Data/Application/EA08B79A-7484-4568-82CE-079B4055CDA7/Documents/15130563374.png, NSUserStringVariant=(
), NSUnderlyingError=0x1c4a4b4c0 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}, { 
    NSUnderlyingError = "Error Domain=NSPOSIXErrorDomain Code=2 \"No such file or directory\""; 

내가 파일을 제거 할 수없는 이유를 잘 모르겠어요 제거의 오류 - 또는 발견되지 반환을 - 때 하나 개의 I로서의 똑같은 파일 경로 에 쓰기. 당신이 코드 을주는 경로에 존재하는지 여부는 파일을 확인 sholud

+1

편집 답변 읽기. 핵심 데이터에 절대로 절대 파일 경로를 저장하면 안됩니다. 응용 프로그램 샌드 박스 자체의 절대 경로가 응용 프로그램 종료 및 실행 사이에 변경되므로 문서 시작의 경로 사이에 문서 디렉토리의 파일 경로가 변경됩니다. –

답변

2

문제는 명확합니다. 파일을 저장 한 파일은

/var/mobile/Containers/Data/Application/EA08B79A-7484-4568-82CE-079B4055CDA7/Documents/15130563374.png 

되고 삭제하려고하는 위치는 잘못된 경로에 이미지를 삭제하려고 그래서 명확하게

/var/mobile/Containers/Data/Application/EA08B79A-7484-4568-82CE-079B4055CDA7/Documents/var/mobile/Containers/Data/Application/EA08B79A-7484-4568-82CE-079B4055CDA7/Documents/15130563374.png 

입니다.

문제 :

collectedLeaf.localImageFilePath = filePath; 

는 이미지 절대 경로와 상대 경로가 아닌 저장한다.그래서

NSString *filePath = [documentsPath stringByAppendingPathComponent:collectedLeaf.localImageFilePath]; 

디렉토리 경로를 따라서 문제의 결과를 문서화하는 이미지의 절대 경로를 추가합니다

솔루션 : 핵심 데이터 파일의

저장 단지 고유 한 이름

collectedLeaf.localImageFilePath = myUniqueName; 

문제를 해결해야합니다.

추가 정보 :

절대로 핵심 데이터에 파일의 절대 경로를 저장하지 마십시오. 문서 디렉토리의 위치는 앱 종료와 시작 사이에서 변경됩니다. 따라서 절대 파일 경로를 저장하는 것은 옵션이 아닙니다. 파일 이름을 저장하고 파일 이름에서 URL을 재구성

+0

파일 이름에서 URL을 재구성합니까? 'fileURLWithPath : collectedLeaf.localImageFileName // previous Path'를 사용하거나'NSArray * paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);가 필요합니다. NSString * documentsPath = [경로 objectAtIndex : 0]; // docs 디렉토리 얻기 NSString * filePath = [문서 경로 stringByAppendingPathComponent : collectedLeaf.localImageFileName]; fileURLWithPath : collectedLeaf.localImageFileName;'? – Matt

+1

@matt : 두 번째 것. 영구 저장소에 절대 파일 경로를 저장하면 안됩니다. 파일 이름 만 만들고 파일 이름에서 절대 URL을 다시 작성하십시오. –

+0

파일 경로 (dataWithContentsOfURL 대 dataWithContentsOfFile)를 통해 URL에 이미지를 액세스 할 때 이점이 있습니까? – Matt

0

첫째, 투표를 아래로

난 당신이 다음 코드를 사용하여 첫 번째 파일 경로에 존재하는지 여부를 확인해야한다고 생각 ,

if ([[NSFileManager defaultManager] fileExistsAtPath:<you file path>]) 
{ 
    // then you can delete your file 
} 
else 
{ 
    NSLog(@"Unresolved error %@, %@", error, [error localizedDescription]) 

} 

파일은 수동으로 해당 파일을 확인해야합니다 당신의 주어진 경로에 존재하지 않는 다음 문제를 찾을 수있을 것입니다 경우

+0

else 문에 어떤 오류 검사를 적용합니까? 위의 코드를 사용할 때 NSLog (@ "미확인 오류 % @, % @", 오류, [error userInfo]);가 위의 코드를 사용할 때 응용 프로그램이 다운 됨 – Matt

+0

@Matt 업데이트 된 응답 –

1

오류 파일 경로

NSFilePath =은/var/모바일/용기/데이터/응용 프로그램/EA08B79A-7484-4568-82CE-079B4055CDA7 살펴 보자

을 /Documents/var/mobile/Containers/Data/Application/EA08B79A-7484-4568-82CE-079B4055CDA7/Documents/15130563374.png 그것은이 URL에 2 documentsPath 있습니다. 제거 할 코어 데이터에서 파일 경로를 가져올 때 documentsPath을 다시 추가하지 않아도됩니다. 제거 코드를 아래 코드로 바꾸십시오.

NSError *error; 
BOOL successDeleteLocalImage = [fileManager removeItemAtPath:collectedLeaf.localImageFilePath error:&error]; 
if(successDeleteLocalImage){ 
    NSLog(@"SUCCESS DELETE IMAGE NO ERROR"); 
    collectedLeaf.localImageFilePath = nil; 
}else{ 
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 
}