How to open pdf file from Documents folder in device Container in swift 4

时间:2018-06-19 11:16:13

标签: ios swift pdf

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..

2 个答案:

答案 0 :(得分:3)

问题是您试图访问的文件显然不是应用程序捆绑包的一部分,因为捆绑包是只读的,因此从Internet下载的文件不会存储在捆绑包中。此外,您提供了Bundle.main.url(forResource :)的完整文件路径,而该函数仅需要绑定文件的本地路径。 您需要使用URL(fileURLWithPath :)而不是Bundle.url(forResource :)。 让pdfUrl = URL(fileURLWithPath:“ file:///var/mobile/Containers/Data/Application/8180A938-D770-48AE-9FC7-ADE939B1D9FA/Documents/myfile.pdf”) 如果让document = PDFDocument(url:path){     pdfView.document =文档 }

答案 1 :(得分:0)

您需要使用以下命令获取文档路径:

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!")
}