Reputation: 843
I have downloaded a pdf file from web service. I have found it in device container.My file location is bellow
file:///var/mobile/Containers/Data/Application/1E4AFEDC-E3A6-4E33-9021-217A61567597/Documents/myfile.pdf
But when i want to open the file from above location then nothing happening. Here is my code..
let pdfView = PDFView()
pdfView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(pdfView)
pdfView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor).isActive = true
pdfView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor).isActive = true
pdfView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
pdfView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true
guard let path = Bundle.main.url(forResource: "file:///var/mobile/Containers/Data/Application/8180A938-D770-48AE-9FC7-ADE939B1D9FA/Documents/myfile", withExtension: "pdf") else { return }
if let document = PDFDocument(url: path) {
pdfView.document = document
}
Please help & suggest me..
Upvotes: 0
Views: 3446
Reputation: 105
In Swift 5 working this code with PDFKit
var pdfURL = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)).last! as URL
pdfURL = pdfURL.appendingPathComponent("myfile.pdf") as URL
pdfView.document = PDFDocument(url: pdfURL )
Upvotes: 0
Reputation: 434
You need to get the Document path with this :
let fileManager = NSFileManager.defaultManager()
let urls = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
if let documentDirectory: NSURL = urls.first as? NSURL {
// This is where the database should be in the documents directory
let finalFileURL = documentDirectory.URLByAppendingPathComponent("myfile.pdf")
if finalFileURL.checkResourceIsReachableAndReturnError(nil) {
// The file already exists, so just return the URL
return finalFileURL
}
} else {
println("Couldn't get documents directory!")
}
Upvotes: 0
Reputation: 54745
The issue is that you are trying to access a file that's clearly not part of the application Bundle, since the Bundle is read-only, so a file downloaded from the internet is not stored in the bundle. Moreover, you supply a full filepath to Bundle.main.url(forResource:)
, whereas that function only expects a local path to bundled files.
You need to use URL(fileURLWithPath:)
instead of Bundle.url(forResource:)
.
let pdfUrl = URL(fileURLWithPath: "file:///var/mobile/Containers/Data/Application/8180A938-D770-48AE-9FC7-ADE939B1D9FA/Documents/myfile.pdf")
if let document = PDFDocument(url: path) {
pdfView.document = document
}
Upvotes: 3