无法从 Swift 中的文档目录加载 pdf

Unable to load pdf from document directory in Swift

我已经从远程服务器下载了一个pdf文件并将其保存在文档目录中。现在我正在尝试检索它并在 webView 中显示 pdf,但我一直收到此异常:

failed to find PDF header: `%PDF' not found.

在此异常之前它也显示此异常:

objc[8087]: Class PLBuildVersion is implemented in both /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/System/Library/PrivateFrameworks/AssetsLibraryServices.framework/AssetsLibraryServices (0x11f29dcc0) and /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/System/Library/PrivateFrameworks/PhotoLibraryServices.framework/PhotoLibraryServices (0x11f0b46f0).

One of the two will be used. Which one is undefined.

但我注意到,当我尝试从移动设备而不是模拟器 运行 时,第二个异常就消失了。下面是我获取它的代码:

    let check:String =  FileNames[0] + ".pdf"
      print("check = \(check)")
 // Method 1
        let docURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        let targetURL = docURL.appendingPathComponent(check)
       
        var request = URLRequest(url: targetURL)
        webView.loadRequest(request)

    /*
           // Method 2
       var pdfURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! as URL
        pdfURL = pdfURL.appendingPathComponent(check) as URL
        print("check url = \(pdfURL)")
        let data = try! Data(contentsOf: pdfURL)
        print("check data = \(data)")
        webView.load(data, mimeType: "application/pdf", textEncodingName:"utf-8", baseURL: pdfURL) // pdfURL.deletingLastPathComponent()
      */
        
        //let requestk = NSURLRequest(url: pdfURL as URL)
       // webView.loadRequest(requestk as URLRequest)
        
        
         // Method 3
        
      /*  let fileManager = FileManager.default
        let documentsUrl = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0] as NSURL
        
        var pdf = documentsUrl.appendingPathComponent(check)
        print("check item fetching from documentsUrl = \(pdf)")
        let req = NSURLRequest(url: pdf!)
        self.webView.loadRequest(req as URLRequest)
      */  

我搜索了很多有关此异常的信息,并遵循了所有可能的解决方案,但 none 的解决方案有效。但是,如果我尝试直接从远程服务器的地址显示此 pdf,它就会显示出来。而且我还检查了这个 pdf 是否正确存储。我已经尝试使用数据方法加载 webView.loadRequest 和 webView.load,也许我遗漏了一些小东西。

更新

  var pdfURL = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)).last! as URL
        print("check final = \(pdfURL)")
        pdfURL = pdfURL.appendingPathComponent(check) as URL
        
        do{
            let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
            let url = URL(fileURLWithPath: path)
            var filePath = url.appendingPathComponent(check).path
            let fileManager1 = FileManager.default
            if fileManager1.fileExists(atPath: filePath) {
                print("FILE AVAILABLE in VC")
              // let fileUrlkk = NSURL(string: filePath)// converting string into URL
                
                filePath = "file://\(filePath)"
                
                let fileUrlkk = Foundation.URL(string: filePath)
                let data = try Data(contentsOf: fileUrlkk!)

               //  let data = try Data(contentsOf: pdfURL) // tried but didn’t work


                self.webView.load(data, mimeType: "application/pdf", textEncodingName:"", baseURL: pdfURL.deletingLastPathComponent())                   
                
            } else {
                print("FILE NOT AVAILABLE in VC")
            }
        }
        catch let error as NSError {
            print("An error took place: \(error)")
        }

它显示“文件在 VC 中可用”,但仍然有这个例外。

使用下面的代码在 WebView 中加载 PDF

Swift 3.0

var pdfURL = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)).last! as URL
pdfURL = pdfURL.appendingPathComponent("Swift.pdf") as URL

let data = try! Data(contentsOf: pdfURL)
self.webView.load(data, mimeType: "application/pdf", textEncodingName:"", baseURL: pdfURL.deletingLastPathComponent())

这里是Document目录下的pdf文件存放路径

/Documents/Swift.pdf

----- 更新 ------

  1. 创建新项目。
  2. 将 1 个示例 PDF 拖入捆绑包 "sample.pdf"
  3. 并使用以下内容更改您的控制器代码
  4. 就是这样 运行

导入 UIKit

class ViewController: UIViewController {

@IBOutlet weak var webView: UIWebView!

override func viewDidLoad() {
    super.viewDidLoad()

    let check = "Swift.pdf"

    var pdfURL = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)).last! as URL
    print("check final = \(pdfURL)")
    pdfURL = pdfURL.appendingPathComponent(check) as URL

    if let pdfBundleURL = Bundle.main.url(forResource: "sample", withExtension: "pdf", subdirectory: nil, localization: nil)  {
        do {
            let data = try Data(contentsOf: pdfBundleURL)

            //Lastly, write your file to the disk.
            try data.write(to: pdfURL, options: .atomicWrite)

        }
        catch {
            // catch errors here
        }
    }

    do{
        let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
        let url = URL(fileURLWithPath: path)
        var filePath = url.appendingPathComponent(check).path
        let fileManager1 = FileManager.default
        if fileManager1.fileExists(atPath: filePath) {
            print("FILE AVAILABLE in VC")
            // let fileUrlkk = NSURL(string: filePath)// converting string into URL

            filePath = "file://\(filePath)"

            let fileUrlkk = Foundation.URL(string: filePath)
            let data = try Data(contentsOf: fileUrlkk!)

            //  let data = try Data(contentsOf: pdfURL) // tried but didn’t work


            self.webView.load(data, mimeType: "application/pdf", textEncodingName:"", baseURL: pdfURL.deletingLastPathComponent())

        } else {
            print("FILE NOT AVAILABLE in VC")
        }
    }
    catch let error as NSError {
        print("An error took place: \(error)")
    }
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

只需使用

do{
  let directoryURL = try manager.url(for:.documentDirectory,in:.userDomainMask, appropriateFor:nil, create:true)

let docURL = NSURL(string:"XXX.pdf", relativeTo:directoryURL)
    }
catch{print("ERROR")
}