I have a file on the iOS iPhone emulator (Download folder).
How can my app get the permission to read this file, in Objective-C? I can get the file path with the following:
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentsDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [docsDirectory stringByAppendingPathComponent:@"file.txt"];
NSLog(@"%@", filePath);
But how can I read it?
CodePudding user response:
Your application is sandboxed and can access files freely only within its own container. For accessing user personal files, you should leverage UIDocumentPickerViewController
class, and let the user pick the file (him/her)self:
UIDocumentPickerViewController *pickerVC = [[UIDocumentPickerViewController alloc] initForOpeningContentTypes:@[
[UTType typeWithFilenameExtension:@"xml"]
]];
pickerVC.delegate = self;
[self presentViewController:pickerVC animated:YES completion:nil];
Then you can access whatever the user selected in the delegate method:
#pragma mark UIDocumentPickerDelegate
- (void)documentPicker:(UIDocumentPickerViewController *)controller
didPickDocumentsAtURLs:(NSArray<NSURL *> *)urls {
NSLog(@"%@", [NSString stringWithContentsOfURL:urls.firstObject
encoding:NSUTF8StringEncoding
error:nil]);
}