在swift中实现文档选择器(iOS) [英] Implement Document Picker in swift (iOS)

查看:1257
本文介绍了在swift中实现文档选择器(iOS)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

Swift中执行此操作的方法

推荐答案

根据项目的功能,启用 iCloud 密钥共享

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

导入 MobileCoreServices 在你的类中,最后在你的UIViewController中扩展了以下三个类:

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

UIDocumentMenuDelegate,UIDocumentPickerDelegate,UINavigationControllerDelegate

实现以下功能:

 public func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {
              let myURL = url as URL
              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 ..

在案例中DropBox。点击任何项目。您将被重定向回您的应用程序,并且该URL将记录在您的终端中。

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.

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

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

kUTTypePDF
kUTTypePNG
kUTTypeJPEG
...

kUTTypePDF kUTTypePNG kUTTypeJPEG ...

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

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") })

< a href =https://i.stack.imgur.com/vYx5c.png =nofollow noreferrer>

享受它。

这篇关于在swift中实现文档选择器(iOS)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆