【发布时间】: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