我已经从Internet成功下载了pdf文件,并将其保存在文档目录中。 网址如下下载文件
file:///Users/heetshah/Library/Developer/CoreSimulator/Devices/4BF83AAF-A910-46EB-AE76-91BC6BEED033/data/Containers/Data/Application/B4532805-2842-431F-B16C-C5E448C8366F/Documents/TPAFForm.pdf
我正尝试将其显示为PDFKit,如下所示。
let path = URL(fileURLWithPath: pdfUrl!)
if let document = PDFDocument(url: path) {
pdfView.document = document
pdfView.displayMode = .singlePageContinuous
pdfView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
pdfView.displaysAsBook = true
pdfView.displayDirection = .vertical
pdfView.autoScales = true
pdfView.maxScaleFactor = 4.0
pdfView.minScaleFactor = pdfView.scaleFactorForSizeToFit
}
我没有收到任何错误
我经历了一堆堆栈溢出帖子,它显示的解决方案与上面相同,但在我的情况下不起作用。 我也尝试了以下解决方案,但不起作用
if let path = Bundle.main.path(forResource: pdfUrl, ofType: "pdf") {
let url = URL(fileURLWithPath: path)
if let pdfDocument = PDFDocument(url: url) {..
以下是我下载文件的代码
func downloadPDF(pdfUrl: String?,fileName: String,completionHandler:@escaping(String,Bool) -> ()){
let destinationPath: DownloadRequest.DownloadFileDestination = {
_,_ in
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let fileURL = documentsURL.appendingPathComponent("\(fileName).pdf")
return (fileURL,[.removePreviousFile,.createIntermediateDirectories])
}
if let pdfUrl = pdfUrl {
Alamofire.download(pdfUrl, to: destinationPath).downloadProgress { (progress) in
}.responseData { (response) in
switch response.result{
case .success:
if response.destinationURL != nil,let filePath = response.destinationURL?.absoluteString{
completionHandler(filePath,true)
}
break
case .failure:
completionHandler("Something went wrong",false)
break
}
}
}
}
我正在使用Alamofire
下载文件。由于我可以在预览中显示在线网址pdf,所以对PDFView的限制是适当的,但是我需要先在本地下载pdf,然后在pdf视图中显示
答案 0 :(得分:2)
由于您没有显示足够的代码来调试问题,因此以下是完整的代码,可以按照您的描述进行操作,您可以通过将代码与我的:
import UIKit
import PDFKit
class ViewController: UIViewController {
let pdfurl = URL(string:"https://www.apeth.com/rez/release.pdf")!
let pdffileurl : URL = {
let fm = FileManager.default
let docsurl = try! fm.url(
for: .documentDirectory, in: .userDomainMask,
appropriateFor: nil, create: true)
return docsurl.appendingPathComponent("mypdf.pdf")
}()
override func viewDidLoad() {
super.viewDidLoad()
let sess = URLSession.shared
sess.downloadTask(with: self.pdfurl) { (url, resp, err) in
if let url = url {
let fm = FileManager.default
try? fm.removeItem(at: self.pdffileurl)
try? fm.moveItem(at: url, to: self.pdffileurl)
DispatchQueue.main.async {
self.displayPDF()
}
}
}.resume()
}
func displayPDF() {
let pdfview = PDFView(frame:self.view.bounds)
pdfview.autoresizingMask = [.flexibleWidth, .flexibleHeight]
pdfview.autoScales = true
self.view.addSubview(pdfview)
let doc = PDFDocument(url: self.pdffileurl)
pdfview.document = doc
}
}