在Filename ios中删除带空格的文件

时间:2016-06-08 07:12:44

标签: ios nsfilemanager

我想删除Documents Directory的图像。该图像具有2016-06-08 12:24:55.897image.jpg种命名约定。

代码段

-(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

我知道找不到文件时会出现错误。由于我使用的命名约定,这种情况正在发生。 我无法改变惯例。有没有办法仍然删除该文件。

1 个答案:

答案 0 :(得分: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]);
}