【问题标题】:Remove File with Space in Filename ios删除文件名中带有空格的文件 ios
【发布时间】:2016-10-08 07:31:26
【问题描述】:

我想删除文档目录的图像。该图像具有这种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

我知道找不到文件时会出现错误。这是由于我使用的命名约定而发生的。 我不能改变约定。有什么办法仍然可以删除文件。

【问题讨论】:

    标签: ios nsfilemanager


    【解决方案1】:

    此代码直接删除文件名

     - (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]);
    }
    

    【讨论】:

    • 试过了,同样的错误Could not delete file -:“2016-06-08 12/52/16.326image” couldn’t be removed.NSError * domain: @"NSCocoaErrorDomain" - code: 4
    • 第二个代码。它位于 if 子句 if ([[NSFileManager defaultManager] isDeletableFileAtPath:path]) 中,但之后出现相同的错误。
    • 有什么办法可以将文件名中的字符转义然后删除。
    • NSCocoaErrorDomain Code = 4 表示您正在尝试移动一个不存在的文件,这也可能意味着目标目录不存在。
    • 这些都没有帮助。我去命名没有特殊字符的图像。这样就解决了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-02
    • 2016-03-29
    • 2020-08-09
    • 2014-08-20
    • 1970-01-01
    • 2020-04-08
    相关资源
    最近更新 更多