基于文档的应用程序

时间:2018-02-14 20:50:19

标签: ios swift document-based

Xcode 9 / iOS 11: 我的应用程序创建了pdf文件,这些文件使用来自核心数据库的数据进行渲染。 pdf是从WebView创建的,存储在文档目录中。到目前为止一切都有效。我可以在Apple的文件应用程序中打开pdf文件,甚至可以在那里编辑它们。我想在我的应用程序中实现DocumentBrowserViewController。我使用了Xcode 9中的模板。我无法像在Apple的文件应用程序中那样在DocumentViewController中显示创建的pdf文件。我可以选择文档,但DocumentViewController只显示文件名和完成按钮。哪个是从模板中显示此DocumentViewController中现有pdf的最简单方法?我在哪里必须实现相关代码?

来自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.
        }
    })
}

这里是来自Xcode 9模板的UIDocument的子类:

类文档: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?
}

}

我在应用开发方面经验不足。我在iTunesU上看Paul Hagerty的课程cs193p关于UIDocument的持久性。但他保存了应用程序的模型,我有一个pdf。有没有简单的方法来显示PDF格式?我尝试了不同的加载pdf的方法,但我不确定是否必须首先创建UIView。文件应用程序中的一个很好的功能是您可以通过电子邮件编辑或发送PDF格式。

1 个答案:

答案 0 :(得分:0)

UIDocumentBrowserViewController的绝佳资源是2017年的WWDC视频:

Building Great Document-based Apps in iOS 11 - WWDC 2017

func load的评论中回答您的问题。是的,您可以在Data获取您的pdf:

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

但是,您应该在DocumentViewController中执行的操作是将fileURL属性UIDocument加载到UIWebView中,以便轻松显示pdf文件。看看这里:https://stackoverflow.com/a/38792456/4089350

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

相关问题