问题描述
为此,我使用了文档选择器,并将文档类型设置为 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
}
如有任何线索,我们将不胜感激!
解决方法
这是快速解决方案,如果有任何问题,请尝试让我知道
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{
}
}
}
,
为了回答我自己的问题,我将在下面留下一个完整的代码。
我的主要问题是,当您使用“public.folder”文档类型时,您需要使用所选文件夹的 url 调用 startAccessingSecurityScopedResource
,而不是使用修改后的链接(用户选择的文件 +新文件名.扩展名)
- (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