PDFView不显示我的PDF

时间:2018-01-07 02:35:28

标签: swift pdf

我无法让我的pdfView显示来自网址的PDF。我可以获取该文件,它根据控制台确实存在。这就是我所做的:

首先,我宣布一个文件选择器:

 @IBAction func addFromICloud(_ sender: UIBarButtonItem) {

    let documentPicker = UIDocumentPickerViewController(documentTypes: ["public.composite-content"], in: .import)
    documentPicker.delegate = self
    documentPicker.modalPresentationStyle = UIModalPresentationStyle.formSheet
    present(documentPicker, animated: true, completion: nil)

}

其次,我从DocumentPickerViewController获取了一个URL和文档名称:

func documentPicker(_ controller: UIDocumentPickerViewController,
                    didPickDocumentAt url: URL) {
    print ("Picker's url is \(url)")
    theName = String(describing:url.lastPathComponent)
    books.append(theName)
    tableView.reloadData()
}

然后,我将theName附加到文档目录路径:

fileIsFromService = true
indexPoint = indexPath.row
let DocumentDirectory = try! FileManager.default.url(for:  .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
docURL = DocumentDirectory.appendingPathComponent(theName)

然后我确保该文件存在,它确实存在:

let fileExists = FileManager().fileExists(atPath: (finalDocURL?.path)!)
print ("The value of fileExists is \(fileExists)")
addressArray.append(docURL!)
print ("The url to be passed should be \(docURL!)")
print ("addressArray is now \(addressArray)")
indexPoint = indexPath.row
viewController.load(books[indexPath.row])

然后,在viewController中,我尝试使用docURL加载pdfView:

func load(_ name: String) {
    if fileIsFromService == true {
        guard let path = docURL else {return}

        if let document = PDFDocument(url: path){
            pdfView.document = document
        }

        pdfView.goToFirstPage(nil)

        if UIDevice.current.userInterfaceIdiom == .pad {
            title = name
        }
    }

我没有错误,只是一个空白的pdfView。我知道已经添加了pdfView的子视图。没有变数是零。我怀疑我需要从docURL中获取数据,但我会在哪里写它?

1 个答案:

答案 0 :(得分:2)

问题是您导入的pdf只是一个临时文件。您需要将临时文件URL复制/移动到您的应用程序文档文件夹。

  

UIDocumentPickerModeImport URL指的是所选内容的副本   文献。该文档是临时文件。它仍然可用   直到您的申请终止。要保留永久副本,您必须   将此文件移动到沙箱中的永久位置。

func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {
    let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    do {
        try FileManager.default.moveItem(at: url.standardizedFileURL, to: documentDirectory.appendingPathComponent(url.lastPathComponent))
        tableView.reloadData()
    } catch {
        print(error)
    }
}