在 swift (iOS) 中实现文档选择器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37296929/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 09:05:43  来源:igfitidea点击:

Implement Document Picker in swift (iOS)

iosswiftuidocumentpickervc

提问by Alexandros

I want to pick a file of any type(.pdf, .docs, .xlsx, .jpeg, .txt, .rtf, etc) functionality in my iOS app. On clicking on Uploadbutton, I want my app to open a directory and select files(DocumentsPicker)

我想在我的 iOS 应用程序中选择任何类型(.pdf、.docs、.xlsx、.jpeg、.txt、.rtf 等)功能的文件。单击上传按钮时,我希望我的应用程序打开一个目录并选择文件(DocumentsPicker

@IBAction pickDocument(sender: UIButton) {
    //Open Document Picker
}

Any approach to do so in Swift?

有什么方法可以这样做Swift吗?

回答by Alexandros

From your project's capabilities, enable both the iCloudand the Key-Sharing.

从项目的能力,同时启用iCloudKey-Sharing

enter image description here

在此处输入图片说明

Import MobileCoreServicesin your class and finally extended the following three classes inside your UIViewController :

MobileCoreServices在您的类中导入并最终在 UIViewController 中扩展以下三个类:

UIDocumentMenuDelegate,UIDocumentPickerDelegate,UINavigationControllerDelegate

Implement the following functions :

实现以下功能:

 public func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
              guard let myURL = urls.first else {
                   return
              }
              print("import result : \(myURL)")
    }


public func documentMenu(_ documentMenu:UIDocumentMenuViewController, didPickDocumentPicker documentPicker: UIDocumentPickerViewController) {
        documentPicker.delegate = self
        present(documentPicker, animated: true, completion: nil)
    }


func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
            print("view was cancelled")
            dismiss(animated: true, completion: nil)
    }

How to call all of this? Add the following bit of code to your click function..

如何调用所有这些?将以下代码添加到您的点击功能中..

func clickFunction(){

let importMenu = UIDocumentMenuViewController(documentTypes: [String(kUTTypePDF)], in: .import)
            importMenu.delegate = self
            importMenu.modalPresentationStyle = .formSheet       
            self.present(importMenu, animated: true, completion: nil)
}

Click your button. The following menu will pop up ..

单击您的按钮。将弹出以下菜单..

MenuPicker

菜单选择器

In the case of DropBox. Upon clicking on any item. You will be redirected back to your app and the URL will be logged in your terminal.

在 DropBox 的情况下。单击任何项​​目后。您将被重定向回您的应用程序,并且 URL 将记录在您的终端中。

enter image description here

在此处输入图片说明

Manipulate the documentTypes to your need. In my app, Users permitted to Pdf only. So, suit yourself.

根据您的需要操作 documentTypes。在我的应用程序中,用户只允许使用 Pdf。所以,适合自己。

kUTTypePDFkUTTypePNGkUTTypeJPEG...

kUTTypePDFkUTTypePNGkUTTypeJPEG...

Also if you feel like customizing your own menu bar. Add the following code and customize your own function inside the handler

此外,如果您想自定义自己的菜单栏。添加以下代码并在处理程序中自定义您自己的函数

        importMenu.addOption(withTitle: "Create New Document", image: nil, order: .first, handler: { print("New Doc Requested") })

enter image description here

在此处输入图片说明

Enjoy it.

好好享受。

回答by pableiros

You can use UIDocumentPickerViewControllerto get the files from the Files apps or iCloud Drive.

您可以使用UIDocumentPickerViewController来从“文件”应用程序或 iCloud Drive 获取文件。

  1. Activate the Key-value storageand iCloud Documentsfrom iCloudcapability:
  1. 激活Key-value storageiCloud Documents来自iCloud功能:

enter image description here

在此处输入图片说明

  1. Import the following framework on the view controller you want to open the document picker:

    import MobileCoreServices
    
  2. Implement the following method from UIDocumentPickerDelegate:

    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
         // you get from the urls parameter the urls from the files selected
    }
    
  3. Create an UIDocumentPickerViewControllerto display the File picker or iCloud Drive:

    let types: [String] = [kUTTypePDF as String]
    let documentPicker = UIDocumentPickerViewController(documentTypes: types, in: .import)
    documentPicker.delegate = self
    documentPicker.modalPresentationStyle = .formSheet
    self.present(documentPicker, animated: true, completion: nil)
    

    If you want the user can import more types of files to your app, you have to add more UTTypes to the typesNSArray. To see all the types available, you can check the UTType Docs

  1. 在要打开文档选择器的视图控制器上导入以下框架:

    import MobileCoreServices
    
  2. 实现以下方法UIDocumentPickerDelegate

    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
         // you get from the urls parameter the urls from the files selected
    }
    
  3. 创建一个UIDocumentPickerViewController以显示文件选择器或 iCloud 驱动器:

    let types: [String] = [kUTTypePDF as String]
    let documentPicker = UIDocumentPickerViewController(documentTypes: types, in: .import)
    documentPicker.delegate = self
    documentPicker.modalPresentationStyle = .formSheet
    self.present(documentPicker, animated: true, completion: nil)
    

    如果您希望用户可以将更多类型的文件导入您的应用程序,您必须UTTypetypesNSArray. 要查看所有可用的类型,您可以查看UTType Docs

When the document picker opens on iOS 11 and you try to select a file inside the Google Drive, it is possible the file is disable due a bug: http://www.openradar.me/24187873

当文档选择器在 iOS 11 上打开并且您尝试选择 Google Drive 中的文件时,该文件可能由于错误而被禁用:http: //www.openradar.me/24187873

回答by SoftDesigner

The UIDocumentMenuViewControlleris deprecated since iOS11. I also found it buggy when presented from a modal view controller. Here's a direct way of using the picker:

UIDocumentMenuViewController自iOS11已被弃用。当从模态视图控制器呈现时,我也发现它有问题。这是使用选择器的直接方法:

import MobileCoreServices

private func attachDocument() {
    let types = [kUTTypePDF, kUTTypeText, kUTTypeRTF, kUTTypeSpreadsheet]
    let importMenu = UIDocumentPickerViewController(documentTypes: types as [String], in: .import)

    if #available(iOS 11.0, *) {
        importMenu.allowsMultipleSelection = true
    }

    importMenu.delegate = self
    importMenu.modalPresentationStyle = .formSheet

    present(importMenu, animated: true)
}

extension AViewController: UIDocumentPickerDelegate, UINavigationControllerDelegate {
    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        viewModel.attachDocuments(at: urls)
    }

     func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
        controller.dismiss(animated: true, completion: nil)
    }
}

As usual don't forget to add iCloud support: iCloud support

像往常一样不要忘记添加 iCloud 支持: iCloud 支持

回答by Sachin Daingade

iCloud access all type of files #

iCloud 访问所有类型的文件#

func openiCloudDocuments(){
    let importMenu = UIDocumentPickerViewController(documentTypes: [String("public.data")], in: .import)
    importMenu.delegate = self
    importMenu.modalPresentationStyle = .formSheet
    self.present(importMenu, animated: true, completion: nil)
}

回答by Duncan C

You could implement what you describe using NSURLSession.

您可以使用NSURLSession.

You will have to limit the target directory you show to your app's documents directory. Apps do not have full access to the file system.

您必须将显示的目标目录限制为应用程序的文档目录。应用程序没有对文件系统的完全访问权限。

回答by Rajesh

this will help you to implement download/upload functionality

这将帮助您实现下载/上传功能

UIDocumentMenuViewController *importMenu = [[UIDocumentMenuViewController alloc] initWithDocumentTypes:@[@"public.item"] inMode:UIDocumentPickerModeImport | UIDocumentPickerModeExportToService];

For more read Apple Documentation

有关更多信息,请阅读Apple 文档

回答by Ben

Something I struggled with was how to specify some specific formats for the PickerView, such as .pptx & .xlsx files. Here's some code to create a PickerView with some commonly required types...

我遇到的问题是如何为 PickerView 指定一些特定的格式,例如 .pptx 和 .xlsx 文件。这里有一些代码来创建一个 PickerView 具有一些通常需要的类型......

let types: [String] = [
    kUTTypeJPEG as String,
    kUTTypePNG as String,
    "com.microsoft.word.doc",
    "org.openxmlformats.wordprocessingml.document",
    kUTTypeRTF as String,
    "com.microsoft.powerpoint.?ppt",
    "org.openxmlformats.presentationml.presentation",
    kUTTypePlainText as String,
    "com.microsoft.excel.xls",
    "org.openxmlformats.spreadsheetml.sheet",
    kUTTypePDF as String,
    kUTTypeMP3 as String
]
let documentPicker = UIDocumentPickerViewController(documentTypes: types, in: .import)
documentPicker.delegate = self
documentPicker.modalPresentationStyle = .formSheet
self.present(documentPicker, animated: true, completion: nil)

There are two places that I found useful in putting together this list:

我发现有两个地方在整理这个列表时很有用:

https://developer.apple.com/library/archive/documentation/Miscellaneous/Reference/UTIRef/Articles/System-DeclaredUniformTypeIdentifiers.html

https://developer.apple.com/library/archive/documentation/Miscellaneous/Reference/UTIRef/Articles/System-DeclaredUniformTypeIdentifiers.html

https://escapetech.eu/manuals/qdrop/uti.html

https://escapetech.eu/manuals/qdrop/uti.html

Hope that helps somebody!

希望对某人有所帮助!