【问题标题】:iOS Creating a file in a public folderiOS 在公共文件夹中创建文件
【发布时间】:2023-04-04 02:50:01
【问题描述】:

我想让用户选择保存新文件的文件夹。

为此,我使用了文档选择器,并将文档类型设置为 public.folder 和 inMode UIDocumentPickerModeOpen

用户打开文档选择器并选择所需的文件夹后,在didPickDocumentsAtURLs 回调中,我获得了 NSUrl 对象,该对象有权修改该 url 处的文件(在本例中,它是文件夹的 url)。

这是我的问题。我拥有对文件夹具有访问权限的 url,但是,要创建一个文件,我通常需要在 url 中有 filename.extension。如果我要修改从文档选择器收到的 NSUrl 对象,或者将其转换为 NSString,我的猜测是我失去了访问权限,createFileAtPath 方法总是失败。

为了在用户选择的路径中创建新文件,我需要使用什么方法,或者我需要什么配置文档选择器?我附上我当前的代码:

- (void)openDocumentPicker:(NSString*)pickerType
{
    //Find the current app window, and its view controller object
    UIApplication* app = [UIApplication sharedApplication];
    UIWindow* rootWindow = app.windows[0];
    UIViewController* rootViewController = rootWindow.rootViewController;
    
    //Initialize the document picker
    UIDocumentPickerViewController *documentPicker = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:@[pickerType] inMode:UIDocumentPickerModeOpen];

    //Assigning the delegate, connects the document picker object with callbacks, defined in this object
    documentPicker.delegate = self;

    documentPicker.modalPresentationStyle = UIModalPresentationFormSheet;

    //Call the document picker, to the view controller that we've found before
    [rootViewController presentViewController:documentPicker animated:YES completion:nil];
}


- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray<NSURL *> *)urls
{
    //If we come here, user successfully picked a file/folder

    [urls[0] startAccessingSecurityScopedResource]; //Let the os know we're going to use the file
        
    NSFileManager *fileManager = [NSFileManager defaultManager];

    NSString *documentsDirectory = urls[0].absoluteString;

    NSString *newFilePath = [documentsDirectory stringByAppendingPathComponent:@"test.txt"];
    NSError *error = nil;
        
    if ([fileManager createFileAtPath:newFilePath contents:[@"new file test" dataUsingEncoding:NSUTF8StringEncoding] attributes:nil]){
        NSLog(@"Create Sucess");
    }
    else{
        NSLog(@"Create error: %@", error);
    }

    [urls[0] stopAccessingSecurityScopedResource]; //Let the os know we're done
}

任何线索将不胜感激!

【问题讨论】:

    标签: ios objective-c file public


    【解决方案1】:

    为了回答我自己的问题,我将在下面留下一个完整的工作代码。

    我的主要问题是,当您使用“public.folder”文档类型时,您需要使用所选文件夹的 url 调用 startAccessingSecurityScopedResource,而不是使用修改后的链接(用户选择的文件 + NewFileName.扩展名)

    - (void)openDocumentPicker
    {
        //This is needed, when using this code on QT!
        //Find the current app window, and its view controller object
        /*
        UIApplication* app = [UIApplication sharedApplication];
        UIWindow* rootWindow = app.windows[0];
        UIViewController* rootViewController = rootWindow.rootViewController;
        */
    
        //Initialize the document picker. Set appropriate document types
        //When reading: use document type of the file, that you're going to read
        //When writing into a new file: use @"public.folder" to select a folder, where your new file will be created
        UIDocumentPickerViewController *documentPicker = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:@[@"public.folder"] inMode:UIDocumentPickerModeOpen];
    
        //Assigning the delegate, connects the document picker object with callbacks, defined in this object
        documentPicker.delegate = self;
    
        documentPicker.modalPresentationStyle = UIModalPresentationFormSheet;
    
        //In this case we're using self. If using on QT, use the rootViewController we've found before
        [self presentViewController:documentPicker animated:YES completion:nil];
    }
    
    - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray<NSURL *> *)urls
    {
        //If we come here, user successfully picked a single file/folder
    
        //When selecting a folder, we need to start accessing the folder itself, instead of the specific file we're going to create
        if ( [urls[0] startAccessingSecurityScopedResource] ) //Let the os know we're going use this resource
        {
            //Write file case ---
        
            //Construct the url, that we're going to be using: folder the user chose + add the new FileName.extension
            NSURL *destURLPath = [urls[0] URLByAppendingPathComponent:@"Test.txt"];
        
            NSString *dataToWrite = @"This text is going into the file!";
        
            NSError *error = nil;
        
            //Write the data, thus creating a new file. Save the new path if operation succeeds
            if( ![dataToWrite writeToURL:destURLPath atomically:true encoding:NSUTF8StringEncoding error:&error] )
                NSLog(@"%@",[error localizedDescription]);
    
        
            //Read file case ---
            NSData *fileData = [NSData dataWithContentsOfURL:destURLPath options:NSDataReadingUncached error:&error];
        
            if( fileData == nil )
                NSLog(@"%@",[error localizedDescription]);
        
            [urls[0] stopAccessingSecurityScopedResource];
        }
        else
        {
            NSLog(@"startAccessingSecurityScopedResource failed");
        }
    }
    

    这也在苹果论坛上进行了讨论:

    线程名称:“iOS 在公用文件夹中创建文件”

    话题链接: https://developer.apple.com/forums/thread/685170?answerId=682427022#682427022

    【讨论】:

      【解决方案2】:

      这是快速解决方案,如果有任何问题,请尝试告诉我

      func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]){
          
          var imgData: Data?
          if let url = urls.first{
              imgData = try? Data(contentsOf: url)
              do{
                  let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
                  let destURLPath = documentDirectory.appendingPathComponent(url.lastPathComponent)
                  try imgData?.write(to: URL(fileURLWithPath: destURLPath))
                  print("FILES IS Writtern at DOcument Directory")
              }catch{
                  
              }
              
              
          }
          
      }
      

      【讨论】:

      • 您好,非常感谢您的回答!我在使用您的代码时遇到了一些问题。我已经成功地将它翻译成objective-c(也在一个swift项目中测试过),我在两种语言上得到的destURLPath是:“/var/mobile/Containers/Data/Application/A788FED2-B5C9-4E39-BC9F-A4052D2F31F5/Documents /文件%20Provider%20Storage”。当我尝试使用 NSData writeToURL 写入 url 时,它失败了。我还尝试修改 url 以添加文件名“/test.txt”并使用 NSFileManager createFileAtPath,这也失败了。我需要如何使用您的代码来创建一个可以写入数据的文件?
      • 你可以制作 swift helper 类来使用相同的代码吗?
      • 你的意思是问,我是否可以在我的原始项目中使用 swift 代码?因为我不这么认为,因为我实际上是在 C++ 项目中实现 Objective-C 代码。但是,如果你能给我提供一个完整的 swift 代码示例,也许我可以将它翻译成 Objective-c!
      • 我已经给了你完整的委托方法,这会很好用
      • 问题是,即使我尝试自己快速运行您的代码,它也会成功运行,但是没有创建文件。我需要添加任何其他代码来创建文件吗?
      猜你喜欢
      • 2016-02-20
      • 2020-02-09
      • 2010-10-06
      • 1970-01-01
      • 2021-12-14
      • 1970-01-01
      • 2014-09-26
      • 1970-01-01
      相关资源
      最近更新 更多