2

Xcode 9 / iOS 11: My app creates pdf-files which are rendered with data from a core data-database. The pdf's are created from a WebView and are stored in the documents directory. Everything works so far. I can open the pdf-files in Apple's Files App and even edit them there. I would like to implement the DocumentBrowserViewController in my app. I used the template from Xcode 9. I'm not able to show the created pdf-files in the DocumentViewController like in Apple's Files App. I can pick the documents but the DocumentViewController shows only the file name and a done-button. Which is the easiest way to show existing pdf's in this DocumentViewController from the template? Where do I have to implement the relevant code?

Code from Xcode9-template:

class DocumentViewController: UIViewController {

@IBOutlet weak var documentNameLabel: UILabel!

var document: UIDocument?

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    // Access the document
    document?.open(completionHandler: { (success) in
        if success {
            // Display the content of the document, e.g.:
            self.documentNameLabel.text = self.document?.fileURL.lastPathComponent

            // --> How to show/load the pdf here? Do I have to create a UIView here first?

        } else {
            // Make sure to handle the failed import appropriately, e.g., by presenting an error message to the user.
        }
    })
}

and here's the subclass of UIDocument from the Xcode 9-template:

class Document: UIDocument {

var pdfData: PreviewViewController?

override func contents(forType typeName: String) throws -> Any {
    // Encode your document with an instance of NSData or NSFileWrapper
    return Data()

}

override func load(fromContents contents: Any, ofType typeName: String?) throws {
   // --> do I have to load the pdf here?
}

}

I'm not very experienced in app-development. I was watching Paul Hagerty's course cs193p on iTunesU about persistence with UIDocument. But he's saving the model of the app and I have a pdf. Is there an easy way to do show the pdf's? I tried different ways to load the pdf but I'm not sure if I have to create a UIView first. The nice feature in Files App is that you can edit or send the pdf via email.

4

1 回答 1

2

一个很好的资源UIDocumentBrowserViewController是 2017 年的 WWDC 视频:

在 iOS 11 中构建出色的基于文档的应用程序 - WWDC 2017

在您的评论中回答您的问题func load。是的,你在这里得到你的pdf Data

override func load(fromContents contents: Any, ofType typeName: String?) throws {
    guard let data = contents as? Data else { return }
}

但是你应该做的是将which 是一个属性DocumentViewController加载到一个可以轻松显示 pdf 文件的中。看看这里:https ://stackoverflow.com/a/38792456/4089350fileURLUIDocumentUIWebView

然后在你的document.open函数中传递fileURL给你的UIWebView.

于 2018-02-15T01:34:04.883 回答