Reputation: 151
I am having trouble getting my pdfView to display a PDF from a URL. I can get the file, and it definitely exists according to the console. Here's what I've done:
First, I declare a document picker:
@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)
}
Second, I get a URL and the name of the document from DocumentPickerViewController:
func documentPicker(_ controller: UIDocumentPickerViewController,
didPickDocumentAt url: URL) {
print ("Picker's url is \(url)")
theName = String(describing:url.lastPathComponent)
books.append(theName)
tableView.reloadData()
}
Then, I append theName to the document directory path:
fileIsFromService = true
indexPoint = indexPath.row
let DocumentDirectory = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
docURL = DocumentDirectory.appendingPathComponent(theName)
Then I make sure that the file exists, and it does:
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])
Then, in viewController, I try to load the pdfView with docURL:
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
}
}
I get no errors, just a blank pdfView. I know that the pdfView's subview has been added. No variables are nil. I suspect that I need to get the data out of docURL, but where would I write it?
Upvotes: 1
Views: 1977
Reputation: 236360
The problem is that the pdf you are importing it is just a temporary file. You need to copy/move the temporary file url to your app documents folder.
UIDocumentPickerModeImport The URL refers to a copy of the selected document. This document is a temporary file. It remains available only until your application terminates. To keep a permanent copy, you must move this file to a permanent location inside your sandbox.
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)
}
}
Upvotes: 3