2016-06-08 76 views
0

我想爲文檔目錄刪除圖像。圖像有這種2016-06-08 12:24:55.897image.jpg種命名約定。用文件名中的空格刪除文件ios

代碼段

-(void) removeImageAtPath:(NSString *) filePath{ 
NSError *error; 
NSFileManager *fileManager = [NSFileManager defaultManager]; 
BOOL success = [fileManager removeItemAtPath:filePath error:&error]; 
if (success) { 
    NSLog(@"Image Successfully Deleted"); 
} 
else{ 
    NSLog(@"Could not delete file -:%@ ",[error localizedDescription]); 
} 
} 

錯誤代碼 NSCocoaErrorDomain Code = 4

我知道如果找不到該文件的錯誤出現。這是因爲我使用的命名約定而發生的。 我無法更改約定。有什麼辦法仍然可以刪除文件。

回答

0

這個代碼刪除文件直接名稱

- (void)removeImage:(NSString *)filename 
    { 
     NSFileManager *fileManager = [NSFileManager defaultManager]; 
     NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 

     NSString *filePath = [documentsPath stringByAppendingPathComponent:filename]; 
     NSError *error; 
     BOOL success = [fileManager removeItemAtPath:filePath error:&error]; 
     if (success) { 
      UIAlertView *removedSuccessFullyAlert = [[UIAlertView alloc] initWithTitle:@"Congratulations:" message:@"Successfully removed" delegate:self cancelButtonTitle:@"Close" otherButtonTitles:nil]; 
      [removedSuccessFullyAlert show]; 
     } 
     else 
     { 
      NSLog(@"Could not delete file -:%@ ",[error localizedDescription]); 
     } 
    } 

其他明智的使用這段代碼

NSError *error; 
if ([[NSFileManager defaultManager] isDeletableFileAtPath:path]) { 
    BOOL success = [[NSFileManager defaultManager] removeItemAtPath:path error:&error]; 
    if (!success) { 
     NSLog(@"Error removing file at path: %@", error.localizedDescription); 
    } 
} 

可以請你試試這個代碼

NSFileManager *fileManager = [NSFileManager defaultManager]; 
NSError *error; 
BOOL fileExists = [fileManager fileExistsAtPath:path]; 
NSLog(@"Path to file: %@", path);   
NSLog(@"File exists: %d", fileExists); 
NSLog(@"Is deletable file at path: %d", [fileManager isDeletableFileAtPath:path]); 
if (fileExists) 
{ 
    BOOL success = [fileManager removeItemAtPath:path error:&error]; 
    if (!success) NSLog(@"Error: %@", [error localizedDescription]); 
} 
+0

試過了,同樣的錯誤'無法刪除文件 - :「2016-06-08 12/52/16.326image」無法刪除。「NSError * \t domain:@」NSCocoaErrorDomain「 - c ode:4 \t' – LeXeR

+0

第二個代碼。它進入if子句'if([[NSFileManager defaultManager] isDeletableFileAtPath:path])',但在此之後給出相同的錯誤。 – LeXeR

+0

是否有任何方法來轉義文件名中的字符,然後刪除。 – LeXeR