【问题标题】:How to rename files/folders from document folder programmatically in iOS如何在 iOS 中以编程方式重命名文档文件夹中的文件/文件夹
【发布时间】:2015-09-18 12:13:54
【问题描述】:

我正在开发将视频文件保存在 iOS 应用程序文件夹中的功能。

如何以编程方式重命名某些文件

【问题讨论】:

标签: ios objective-c file-rename


【解决方案1】:

试试这个代码:

NSError * err = NULL;
NSFileManager * fm = [[NSFileManager alloc] init];
BOOL result = [fm moveItemAtPath:@"/tmp/test.tt" toPath:@"/tmp/dstpath.tt" error:&err];
if(!result)
    NSLog(@"Error: %@", err);

否则使用此方法重命名文件

- (void)renameFileWithName:(NSString *)srcName toName:(NSString *)dstName
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *filePathSrc = [documentsDirectory stringByAppendingPathComponent:srcName];
    NSString *filePathDst = [documentsDirectory stringByAppendingPathComponent:dstName];
    NSFileManager *manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePathSrc]) {
        NSError *error = nil;
        [manager moveItemAtPath:filePathSrc toPath:filePathDst error:&error];
        if (error) {
            NSLog(@"There is an Error: %@", error);
        }
    } else {
        NSLog(@"File %@ doesn't exists", srcName);
    }
}

【讨论】:

    【解决方案2】:

    没有用于重命名文件的直接 API。虽然当您将文件从一个地方移动到另一个地方时,如果目标路径中的该文件不存在,那么 iOS 将以给定名称创建该文件。对于文件,您可以只给出文件的新名称,它应该如何显示/引用。

    you could check this answer. Good luck!

    【讨论】:

      猜你喜欢
      • 2017-08-27
      • 2022-10-15
      • 1970-01-01
      • 2011-12-30
      • 2020-04-30
      • 1970-01-01
      • 1970-01-01
      • 2015-02-06
      • 1970-01-01
      相关资源
      最近更新 更多