ios - 在 Swift 4 中显示 PDF 文件

标签 ios swift pdf webview

import UIKit
import WebKit

class ViewController: UIViewController, UIDocumentInteractionControllerDelegate {

    var docController: UIDocumentInteractionController!

    override func viewDidLoad() {
        super.viewDidLoad()

        docController = UIDocumentInteractionController.init(url: URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(urlVal!))
        docController.delegate = self
        docController.presentPreview(animated: true)       
    }


    func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
            return self
     }
}

以上代码我无法显示 pdf 文件。谁能帮忙?

最佳答案

通过查看您的代码,您似乎错过了添加 UIDocumentInteractionControllerDelegate 委托(delegate)方法。

    class ViewController: UIViewController,UIDocumentInteractionControllerDelegate {
        override func viewDidLoad() {
            super.viewDidLoad()

           var docController = UIDocumentInteractionController.init(url: URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(urlVal!))
            docController.delegate = self
            docController.presentPreview(animated: true)
        }
        func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
            return self
        }
    }

您还可以通过将 PDF 加载到 WKWebView 来查看它。

    override func viewDidLoad() {
        super.viewDidLoad()

        let pdfFilePath = Bundle.main.url(forResource: "iostutorial", withExtension: "pdf")
        let urlRequest = URLRequest.init(url: pdfFilePath!)
        webView = WKWebView(frame: self.view.frame)
        webView.load(request)
        self.view.addSubview(webView)

    }

enter image description here

关于ios - 在 Swift 4 中显示 PDF 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48577112/

相关文章:

ios - 无法约束将 UIView 固定到单元格 contentView 的底部

ios - Swift 中的 PureLayout 与 Cocoapods

pdf - 使用文本搜索选项在我的 iPad 应用程序中打开 pdf 文件

java - pdf解析为java中的文本

pdf - 将 PDF 转换为 Word

objective-c - MKAnnotationView 帧大小在缩放之前不会更新 MapView

ios - 使用特定关键字从结构填充 UITableView

ios - 为什么lazy property和didSet会以递归调用结束?

iphone - 为 iPad 设置图标,应用程序的目标设备是 iPhone

ios - 快速删除plist