UIDocumentPickerViewController

UIDocumentPickerViewController

UIDocumentPickerViewController:

A view controller that provides access to documents or destinations outside your app’s sandbox.
可以访问沙盒外的文档 or 目标

可以使用document picker view controller来选择文档,进行导入,导出,打开 or 移动 (importing, exporting, opening, or moving)

Document Picker Modes

支持四种模式:

  • Import an external document - 用户选择外部的文档,document picker复制这个文档,原来的文件不变
  • Export a local document - 用户选择一个外部的destination,document picker复制这个文档,原来的文件不变
  • Open an external document - 用户选择一个外部的文档,document picker提供对这个文档的访问,用户可以编辑文档
  • Move a local document - 用户选择一个外部的destination,document picker移动这个文档。然而,用户任然可以把文档作为外部文档来访问,且用户可以编辑文档

UIDocumentPickerViewController有个代理UIDocumentPickerDelegate,在其documentPicker:didPickDocumentsAtURLs:中,对上面的模式也有说明:

  • UIDocumentPickerModeImport - url指向复制的文件。这个文件是临时文件,它们保持可以直至应用程序终结。要想持久持有,可以将这些文件移动到沙盒中
  • UIDocumentPickerModeOpen - url指向选中的文档。The provided URL is a security-scoped URL referring to a file outside your app’s sandbox. For more information on working with external, security-scoped URLs, see Requirements.
  • UIDocumentPickerModeExportToService - The URL refers to the new copy of the exported document at the selected destination. This URL refers to a file outside your app’s sandbox. You cannot access this copy; the URL is passed only to indicate success
  • UIDocumentPickerModeMoveToService - The URL refers to the document’s new location. The provided URL is a security-scoped URL referring to a file outside your app’s sandbox. For more information on working with external, security-scoped URLs, see Requirements.

要想你app的文件在files app中出现,一般要在Info.plist设置如下的2个key:

  • UIFileSharingEnabled - 可以从iTunes中导入文件到Documents文件夹中
  • LSSupportsOpeningDocumentsInPlace - 确保local file provider可以访问你的Documents文件夹

01
网上的教程和官方文档Document Picker Programming Guide都要求做如下的设置:

Before your app can use the document picker, you must turn on the iCloud Documents capabilities in Xcode. For more information about iCloud Documents, see Designing for Documents in iCloud.
02

如上设置之后,如果Documents文件夹中没有文件,貌似是不会在Files App中展示当前App的文件夹的。如果Documents文件夹中有文件,则会展示

IOS8 DAY-BY-DAY :: DAY 28 :: DOCUMENT PICKER中的例子来说明

Import形式

如下的形式,选择一张图片导入:

- (IBAction)import:(id)sender {
    
    UIDocumentPickerViewController *documentPicker = [[UIDocumentPickerViewController alloc]
                                                      initWithDocumentTypes:@[@"public.image"] inMode:UIDocumentPickerModeImport];
    documentPicker.delegate = self;
    documentPicker.modalPresentationStyle = UIModalPresentationFormSheet;
    [self presentViewController:documentPicker animated:YES completion:nil];
    
}

#pragma mark - UIDocumentPickerDelegate

- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray<NSURL *> *)urls {
    
    if (controller.documentPickerMode == UIDocumentPickerModeImport) {
        NSString *alertMessage = [NSString stringWithFormat:@"Successfully imported %@", [[urls lastObject] lastPathComponent]];
        dispatch_async(dispatch_get_main_queue(), ^{
            UIAlertController *alertController = [UIAlertController
                                                  alertControllerWithTitle:@"Import"
                                                  message:alertMessage
                                                  preferredStyle:UIAlertControllerStyleAlert];
            [alertController addAction:[UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:nil]];
            [self presentViewController:alertController animated:YES completion:nil];
        });
    }
    
}

效果如下:
01
Export形式

如下的例子,导出一个名为App.pdf的文件

- (IBAction)exprot:(id)sender {
    
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"App" withExtension:@"pdf"];
    UIDocumentPickerViewController *documentPicker = [[UIDocumentPickerViewController alloc] initWithURL:url
                                                                                            inMode:UIDocumentPickerModeExportToService];
    documentPicker.delegate = self;
    documentPicker.modalPresentationStyle = UIModalPresentationFormSheet;
    [self presentViewController:documentPicker animated:YES completion:nil];
    
    
}

02
03
04
参考文档:

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
iOS 中没有一个通用的文件管理器,但是可以使用 UIDocumentPickerViewController 来让用户选择并打开文本文件。以下是一个简单的示例代码: 1. 导入框架: ``` import UIKit import MobileCoreServices ``` 2. 创建一个UIViewController来展示文本内容: ``` class TextFileViewController: UIViewController { @IBOutlet weak var textView: UITextView! var url: URL? // 用来获取用户选择文件的URL override func viewDidLoad() { super.viewDidLoad() if let url = url { do { let text = try String(contentsOf: url, encoding: .utf8) textView.text = text } catch { print(error.localizedDescription) } } } } ``` 3. 在需要打开文件的地方,使用 UIDocumentPickerViewController: ``` let documentPicker = UIDocumentPickerViewController(documentTypes: [String(kUTTypePlainText)], in: .import) documentPicker.delegate = self present(documentPicker, animated: true, completion: nil) ``` 4. 添加 UIDocumentPickerDelegate: ``` extension ViewController: UIDocumentPickerDelegate { func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) { if let url = urls.first { let storyboard = UIStoryboard(name: "Main", bundle: nil) if let textFileViewController = storyboard.instantiateViewController(withIdentifier: "TextFileViewController") as? TextFileViewController { textFileViewController.url = url navigationController?.pushViewController(textFileViewController, animated: true) } } } } ``` 这样就可以让用户选择并打开文本文件,并在 TextFileViewController 中展示文件内容。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值