【问题标题】:iOS Document Picker crashes when picking a PDF on a real device在真实设备上选择 PDF 时 iOS 文档选择器崩溃
【发布时间】:2020-11-01 13:50:20
【问题描述】:

我尝试为我的 iOS 应用创建一个文档选择器。

这是我的代码(我将 UIDocumentPickerViewController 包装在我的 SwiftUI 视图中,使用 UIViewControllerRepresentable):

import SwiftUI
import MobileCoreServices

struct DocumentPickerViewController: UIViewControllerRepresentable {
    var callback: (Data) -> ()

    func makeCoordinator() -> Coordinator {
        return Coordinator(documentController: self)
    }

    func updateUIViewController(
        _ uiViewController: UIDocumentPickerViewController,
        context: UIViewControllerRepresentableContext<DocumentPickerViewController>) {
    }

    func makeUIViewController(context: Context) -> UIDocumentPickerViewController {
        let controller = UIDocumentPickerViewController(documentTypes: [String(kUTTypePDF)], in: .open)
        controller.delegate = context.coordinator
        return controller
    }

    class Coordinator: NSObject, UIDocumentPickerDelegate {
        var documentController: DocumentPickerViewController

        init(documentController: DocumentPickerViewController) {
            self.documentController = documentController
        }

        func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
            guard let url = urls.first else { return }

            let fileManager = FileManager.default
            print(fileManager.fileExists(atPath: url.path))
            let data = NSData(contentsOfFile: url.path)
            let file = UploadFileData(fileName: "\(url)", fileType: .file, fileData: data!)
            let dataFile = file.fileData as Data
            
            documentController.callback(dataFile)
        }
    }
}

enum UploadFileType{
    case photo
    case file
}

struct UploadFileData {
    var fileName: String
    var fileType: UploadFileType
    var fileData: NSData
}

var file: UploadFileData?

它可以在我的模拟器上运行,但是当我在真实设备上选择 PDF 时,我收到以下错误: 致命错误:在展开可选值时意外发现 nil:文件 MyApp/DocumentPickerViewController.swift,第 44 行

即换行:let dataFile = file.fileData as Data

【问题讨论】:

    标签: ios swift xcode swiftui


    【解决方案1】:

    存在的问题是您在定义文档选择器使用的文件传输操作类型时使用了错误的模式。 .open 用于打开位于应用沙箱之外的外部文件。您需要使用.import,它将创建一个临时文件,允许您加载其内容或将文件移动/复制到永久位置。如果它不能解决您的问题,请查看post,了解如何实现您的 DocumentPickerViewController 协调器

    let controller = UIDocumentPickerViewController(documentTypes: [String(kUTTypePDF)], in: .import)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多