如何使数组包含PDF文档

时间:2019-03-26 00:41:17

标签: ios arrays swift if-statement

我是新手,很快就尝试找出如何编码数组以包含PDF文档的方法。我设置了一个tableView,因为单击单元格时它将移至新的详细信息视图控制器。我希望新的明细控制器显示与所选单元格关联的PDF。有一种聪明的方式对此进行编码吗?

我一直在努力编写这部分代码。

import Foundation
import UIKit
import PDFKit

class State
{
    var title: String
    var detailText: String
    var description: String
    var image: UIImage

    var document: PDFDocument

    init(titled: String, detailText: String, imageName: String, description: String, document: String)
    {
        self.title = titled
        self.detailText = detailText
        self.description = description

        self.document = PDFDocument

        if let img = UIImage(named: imageName){
            image = img
        } else {
            image = UIImage(named: "default")!
        }
    }
}

我正在尝试获取将“文档”识别为PDFDocument的代码,但出现错误:无法将“ PDFDocument.Type”类型的值分配为“ PDFDocument”类型,这是我哪里出了问题?

1 个答案:

答案 0 :(得分:1)

导致错误的原因是您试图将类型(PDFDocument)分配给self.document,而不是传递给init-document的参数。此外,参数的类型必须为PDFDocument,而不是String

import Foundation
import UIKit
import PDFKit

class State
{
    var title: String
    var detailText: String
    var description: String
    var image: UIImage

    var document: PDFDocument

    init(titled: String, detailText: String, imageName: String, description: String, document: PDFDocument)
    {
        self.title = titled
        self.detailText = detailText
        self.description = description

        self.document = document

        if let img = UIImage(named: imageName){
            image = img
        } else {
            image = UIImage(named: "default")!
        }
    }
}

除非出于某些其他原因而需要 State成为类,否则我建议将其设置为结构-这将提供隐式不变性。您还可以使用nil合并运算符来简化if语句

import Foundation
import UIKit
import PDFKit

struct State
{
    var title: String
    var detailText: String
    var description: String
    var image: UIImage
    var document: PDFDocument

    init(titled: String, detailText: String, imageName: String, description: String, document: PDFDocument)
    {
        self.title = titled
        self.detailText = detailText
        self.description = description

        self.document = document
        self.image = UIImage(named: imageName) ?? UIImage(named: "default")!
    }
}

好吧

看来您的实际问题是“如何从应用程序捆绑包中获取PDFDocument?”。

您可以使用以下内容:

if let path = Bundle.main.path(forResource: "SomePdfFile", ofType: "pdf") {
      do {
          let fileUrl = URL(fileURLWithPath: path)
          if let pdfDocument = PDFDocument(url:fileURL) {
              // Do something with PDFDocument
          }
      } catch {
          print("There was an error - \(error)")
      }
}

您可以将其转换为功能:

func loadPDF(named: String) throws -> PDFDocument? {
    guard let path = Bundle.main.path(forResource: "SomePdfFile", ofType: "pdf") else {
        return nil
   }

   let fileUrl = URL(fileURLWithPath: path)
   return PDFDocument(url:fileURL)
}