【问题标题】:NSFileManager createDirectoryAtPath method returns true but no directory was createdNSFileManager createDirectoryAtPath 方法返回 true 但没有创建目录
【发布时间】:2021-12-15 23:58:57
【问题描述】:

在我的应用程序中,我想创建一个目录并将一些 txt 文件放入其中。这是我创建目录的代码

-(BOOL)createFolderInDocuments:(NSString *)folderName
{
    NSError *error = nil;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:folderName];
    
    BOOL success = YES;
    if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
        success = [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];
    
    if(error){
        UIAlertController * alert = [UIAlertController
                                     alertControllerWithTitle:@"Error"
                                     message:[NSString stringWithFormat:@"Create folder: %@", error]
                                     preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* okButton = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action){}];
        [alert addAction:okButton];
        [self presentViewController:alert animated:YES completion:nil];
    }
    
    if (success) {
        NSLog(@"Created folder with name %@", folderName);
    }
    return success;
}

运行该方法后,我在控制台中收到此消息

2021-11-01 15:16:23.786293+0800 my-app[887:167944] Created folder with name 2021-11-01T15-16-23

这意味着方法createDirectoryAtPath返回了true

根据我使用此 repo https://github.com/Varvrar/ios_logger 的经验,在我运行该方法后,我应该在 Finder 位置获得一个包含我的应用程序名称的文件夹,如下所示。

但我在这里什么都没有。实际上,我在 iPhone 上的任何地方都找不到该目录。所以我猜它根本没有被创建。

谁能告诉我如何正确创建目录?谢谢!

【问题讨论】:

  • “但我这里什么也没有” “这里”到底在哪里?您只能在分配给您的应用的沙盒文件夹中创建一个文件夹。
  • 抱歉,我不知道它在 iPhone 上的确切位置。我可以通过本教程support.apple.com/en-us/HT210598 中的“查看可以与 Mac 共享文件的 iOS 和 iPadOS 应用”部分找到它
  • 使用 NSLog 打印 dataPath guy。
  • @El Tomato 我做到了,结果是“/var/mobile/Containers/Data/Application/73E4106A-B108-4CEA-B7E3-F829CF861577/Documents/2021-11-01T16-23- 56"

标签: ios objective-c nsfilemanager


【解决方案1】:

好的,我想通了。该目录确实创建了,只是当 iPhone 连接到 Mac 时,它没有显示在 Finder 中。

为了让它在 Finder 中显示,请在 xcode 项目 info.plist 中添加此权利

【讨论】:

    猜你喜欢
    • 2013-02-21
    • 2011-06-22
    • 1970-01-01
    • 1970-01-01
    • 2014-06-16
    • 2019-09-08
    • 2023-03-21
    • 2020-05-03
    • 1970-01-01
    相关资源
    最近更新 更多