如何在iOS Swift的“Gallery”中显示可用的PDF文档?

58wvjzkj  于 2022-10-31  发布在  Swift
关注(0)|答案(2)|浏览(150)

我不知道这个叫什么。但是我需要做一个类似的东西,就像这个一样
因此,如果我想从照片库中选择一个图像,按下按钮后,视图控制器将显示如下(如果使用UIImagePickerController


但我需要在上传pdf或doc文件到服务器之前做一些类似的事情,这样用户就可以在他们的iPhone或远程存储中选择文档
类似于Mac的东西,
按下按钮

然后选择文件

如何在Swift中为iPhone执行此操作?

xeufq47z

xeufq47z1#

就我了解到的您的需求而言,FilesProvider有一个API,您可以通过其他应用程序与它交互,
了解更多信息here
这是一个很好的教程here
这将使您很好地了解API的工作原理以及FileProvider在iOS中的工作原理

kgsdhlau

kgsdhlau2#

您需要查看此文档选择器
see this link
从以上链接复制
iOS 14已弃用此方法

public init(documentTypes allowedUTIs: [String], in mode: UIDocumentPickerMode)

在按钮操作中编写此代码

@IBAction func importItemFromFiles(sender: UIBarButtonItem) {

     var documentPicker: UIDocumentPickerViewController!
     if #available(iOS 14, *) {
         // iOS 14 & later
         let supportedTypes: [UTType] = [UTType.image]
         documentPicker = UIDocumentPickerViewController(forOpeningContentTypes: supportedTypes)
     } else {
         // iOS 13 or older code
         let supportedTypes: [String] = [kUTTypeImage as String]
         documentPicker = UIDocumentPickerViewController(documentTypes: supportedTypes, in: .import)
     }
     documentPicker.delegate = self
     documentPicker.allowsMultipleSelection = true
     documentPicker.modalPresentationStyle = .formSheet
     self.present(documentPicker, animated: true)
 }

实作委派

// MARK: - UIDocumentPickerDelegate Methods

  extension MyViewController: UIDocumentPickerDelegate {
    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {

        for url in urls {

            // Start accessing a security-scoped resource.
            guard url.startAccessingSecurityScopedResource() else {
                // Handle the failure here.
                return
            }

            do {
                let data = try Data.init(contentsOf: url)
                // You will have data of the selected file
            }
            catch {
                print(error.localizedDescription)
            }

            // Make sure you release the security-scoped resource when you finish.
            defer { url.stopAccessingSecurityScopedResource() }
        }
    }

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

相关问题