【问题标题】:Document-Based Application基于文档的应用程序
【发布时间】:2018-07-25 13:02:18
【问题描述】:

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

来自 Xcode9 模板的代码:

类 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。 Files App 中的一个不错的功能是您可以编辑或通过电子邮件发送 pdf。

【问题讨论】:

  • 我@Fario,您能否将您使用的代码包含在您的DocumentViewController 中,这样我们就可以看到您到目前为止尝试了什么?谢谢!

标签: ios swift document-based


【解决方案1】:

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

Building Great Document-based Apps in 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 }
}

但是您应该在DocumentViewController 中将fileURLUIDocument 的属性)加载到可以轻松显示pdf 文件的UIWebView 中。看看这里:https://stackoverflow.com/a/38792456/4089350

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

【讨论】:

  • 太好了,谢谢!我创建了一个函数来获取 URL,然后将数据加载到 WKWebView 中。 func load 中的代码甚至没有必要。首先,我认为我可以使用与 Files App 中相同的功能,您可以在其中使用彩色铅笔编辑 pdf 文件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多