【问题标题】:Imagepath Replace in Document Directory文档目录中的图像路径替换
【发布时间】:2016-05-19 04:57:15
【问题描述】:

对于使用NSFileManager,如果存在图像路径或文件夹,如何替换新的图像路径(或)文档目录中的文件夹。

NSFileManager 有替换功能吗? (如何在文档目录中用新的图片路径替换图片路径位置)

【问题讨论】:

  • 使用您想要替换的相同路径并再次写入您的文件将被替换为@metronic 所说的

标签: ios objective-c iphone nsfilemanager nsdocumentdirectory


【解决方案1】:

您想改写图像,只需将其写入文件即可。 如果同一路径下存在同名图片,会被覆盖

NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;

UIImage * imageToSave = [UIImage imageNamed:@"Icon.png"];
NSData * binaryImageData = UIImagePNGRepresentation(imageToSave);

[binaryImageData writeToFile:[basePath  stringByAppendingPathComponent:@"myfile.png"] atomically:YES];

【讨论】:

    【解决方案2】:

    您不能使用 NSFileManager 替换路径,因为您已经保存了 ImagePath。现在您可以检查该路径是否存在,然后您可以使用以下命令删除该 filePath:

    if ([fileManager fileExistsAtPath:Path] == YES) {
      [fileManager removeItemAtPath:Path error:&error];
    }
    

    现在保存您的新路径。

    如果要替换内容,则先简单删除,然后再次使用

    writeToFile:filePath
    

    【讨论】:

    • 如果删除旧文件则不需要。它会自动替换为新图像。
    【解决方案3】:
        NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        NSString* foofile = [documentsPath stringByAppendingPathComponent:filename];
        BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:foofile];
        NSLog(fileExists ? @"Yes" : @"No");
        if (fileExists == YES)
        {
            NSString *filePath = [NSString stringWithFormat:@"%@/%@", aDocumentsDirectory,filename];
            NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(image)];
            [data1 writeToFile:filePath atomically:YES];
        }
    

    【讨论】:

      猜你喜欢
      • 2016-09-19
      • 1970-01-01
      • 1970-01-01
      • 2018-02-13
      • 2014-10-01
      • 2013-02-02
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多