我想在我的iOS应用程序中 Select 任何类型(.pdf、.docs、.xlsx、.jpeg、.txt、.rtf等)功能的文件.点击Upload按钮,我希望我的应用程序打开一个目录并 Select 文件(DocumentsPicker
)
@IBAction pickDocument(sender: UIButton) {
//Open Document Picker
}
有没有办法在Swift
年内做到这一点?
我想在我的iOS应用程序中 Select 任何类型(.pdf、.docs、.xlsx、.jpeg、.txt、.rtf等)功能的文件.点击Upload按钮,我希望我的应用程序打开一个目录并 Select 文件(DocumentsPicker
)
@IBAction pickDocument(sender: UIButton) {
//Open Document Picker
}
有没有办法在Swift
年内做到这一点?
Update for iOS 14:你不需要任何能力.只要用适当的类型创建一个UIDocumentPickerViewController
,实现委托,你就完成了.
更多信息in this answer.代码如下:
import UIKit
import MobileCoreServices
import UniformTypeIdentifiers
func selectFiles() {
let types = UTType.types(tag: "json",
tagClass: UTTagClass.filenameExtension,
conformingTo: nil)
let documentPickerController = UIDocumentPickerViewController(
forOpeningContentTypes: types)
documentPickerController.delegate = self
self.present(documentPickerController, animated: true, completion: nil)
}
从项目的功能中,启用iCloud
和Key-Sharing
.
在类中导入MobileCoreServices
,然后在UIViewController
中扩展以下三个类:
UIDocumentMenuDelegate,UIDocumentPickerDelegate,UINavigationControllerDelegate
实现以下功能:
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)
}
你怎么称呼这一切?向单击功能中添加以下代码:
func clickFunction(){
let importMenu = UIDocumentMenuViewController(documentTypes: [String(kUTTypePDF)], in: .import)
importMenu.delegate = self
importMenu.modalPresentationStyle = .formSheet
self.present(importMenu, animated: true, completion: nil)
}
点击你的按钮.将弹出以下菜单..
就Dropbox而言.点击任何一项.你将被重定向回你的应用程序,URL将被登录到你的终端.
根据需要操作文档类型.在我的应用程序中,用户只允许使用Pdf.所以,随你的便.
kUTTypePDF
如果你想定制你自己的菜单栏.添加以下代码并在处理程序中自定义自己的函数
importMenu.addOption(withTitle: "Create New Document", image: nil, order: .first, handler: { print("New Doc Requested") })
享受吧.