我想在我的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)
}


从项目的功能中,启用iCloudKey-Sharing.

enter image description here

在类中导入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)
}

点击你的按钮.将弹出以下菜单..

MenuPicker

就Dropbox而言.点击任何一项.你将被重定向回你的应用程序,URL将被登录到你的终端.

enter image description here

根据需要操作文档类型.在我的应用程序中,用户只允许使用Pdf.所以,随你的便.

kUTTypePDF

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

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

enter image description here

享受吧.

Swift相关问答推荐

VisionOS发送通知

使用SWIFT宏从另一个枚举添加 case

如何把多个可观测性变成一个完备性?

我在SwiftUI中的动画无法正常工作

如何在DATE()中进行比较

如何强制创建新的UIViewControllerRenatable|更新Make UIViewController上的视图

SwiftData/PersistentModel.swft:540:致命错误:不支持的关系密钥路径ReferenceWritableKeyPath

在 init(from decoder: Decoder) 方法中访问原始 JSON 数据

如何在 swiftui 中设置给定字符串类型日期的日期倒计时?

如何制作进度加载动画?

SwiftUI 动画的范围

如何在 SwiftUI 中获取视图的位置

在 Select 器上显示alert Select SwiftUI

在 xcode 13 中的构建之间保持可访问性权限

仅在 Swift 中创建 Setter

在 ViewController 的 UICollectionView 中拉取刷新

无法推断泛型参数的参数

Swift 2.0 中的 do { } catch 不处理从这里抛出的错误

<<错误类型>> 奇怪的错误

使用 ARAnchor 插入 node 和直接插入 node 有什么区别?