Подтвердить что ты не робот

Открыть файл PDF с помощью быстрого

Как добавить файл PDF для приложения, где вы нажимаете кнопку, чтобы просмотреть файл, и когда вы закончите, вы вернетесь к экрану, на котором вы были?

4b9b3361

Ответ 1

Если вы просто хотите просмотреть файл PDF, вы можете загрузить его в UIWebView.

let url : NSURL! = NSURL(string: "http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIWebView_Class/UIWebView_Class.pdf")
webView.loadRequest(NSURLRequest(URL: url))

Swift 4.1:

let url: URL! = URL(string: "http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIWebView_Class/UIWebView_Class.pdf")
webView.loadRequest(URLRequest(url: url))

Если вы хотите достичь большего, то хорошим фреймворком является PSPDFKit.

Ответ 2

SWIFT 4+

Если должен открыть файл из локального кэша /Documentdiectory, который имеет путь к файлу

Способ 1: использование UIDocumentInteractionController

class ViewController: UIViewController,UIDocumentInteractionControllerDelegate {
   //let path =  Bundle.main.path(forResource: "Guide", ofType: ".pdf")!
    let dc = UIDocumentInteractionController(url: URL(fileURLWithPath: path))
    dc.delegate = self
    dc.presentPreview(animated: true)
 }
   //MARK: UIDocumentInteractionController delegates
func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
     return self//or use return self.navigationController for fetching app navigation bar colour
 }

Способ 2: использование WebView

  let webview = WKWebView(frame: UIScreen.main.bounds)
  view.addSubview(webview)
  webview.navigationDelegate = self
  webview.load(URLRequest(url: URL(fileURLWithPath: path)))//URL(string: "http://") for web URL

Ответ 3

Apple добавила каркас PDFKit в iOS 11

Добавьте UIView к вашему контроллеру представления и сделайте его классом для PDFView

enter image description here

import UIKit
import PDFKit

class ViewController: UIViewController {

    @IBOutlet var pdfView: PDFView!

    override func viewDidLoad() {
        super.viewDidLoad()

        if let path = Bundle.main.path(forResource: "sample", ofType: "pdf") {
            if let pdfDocument = PDFDocument(url: URL(fileURLWithPath: path)) {
                pdfView.displayMode = .singlePageContinuous
                pdfView.autoScales = true
                pdfView.displayDirection = .vertical
                pdfView.document = pdfDocument
            }
        }
    }
}

Существует 4 режима отображения: singlePage, singlePageContinuous, twoUp, twoUpContinuous.

Ответ 4

Для Xcode 8.1 и Swift 3.0

Сохраните файл PDF в любой папке вашего xcode. Предположим, что имя файла "Filename.pdf"

 if let pdf = Bundle.main.url(forResource: "Filename", withExtension: "pdf", subdirectory: nil, localization: nil)  {
    let req = NSURLRequest(url: pdf)
    yourWebViewOutletName.loadRequest(req as URLRequest)        
  }

То же самое применимо, если вы хотите открыть любой html файл.

Ответ 5

Вы можете использовать UIDocumentInteractionController для предварительного просмотра файла в IOS. В файле контроллера представления добавьте свойство типа UIDocumentInteractionController

и реализовать простой метод делегата этого

self.documentInteractionController = UIDocumentInteractionController.init(URL: url)
self.documentInteractionController?.delegate = self
self.documentInteractionController?.presentPreviewAnimated(t‌​rue) 

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

не забудьте добавить UIDocumentInteractionControllerDelegate в класс контроллера представления

Ответ 6

Вы также можете использовать Quick Look Framework от Apple.

Он очень гибкий.

Вы можете показать свой файл PDF с функцией масштабирования.

Также у вас есть поддержка всех других типов (например, png, jpg, docx, txt, rtf, xlsx, zip, mov и т.д.) файлов, и это очень просто использовать.

Пожалуйста, обратитесь this ответьте, если вы хотите подробное описание использования QuickLook.framework

Ответ 7

Вы можете использовать этот код в Swift 4

  1. Импортировать PDFKit
  2. Скопируйте этот код

    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: "test", withExtension: "pdf") else { return }
    
    if let document = PDFDocument(url: path) {
        pdfView.document = document
    }
    

Ответ 8

let openLink = NSURL(string : self.OtherContactorProfileVview.Result.CertificateList[index].CertificateFileLink)

        if #available(iOS 9.0, *) {
            let svc = SFSafariViewController(url: openLink! as URL)
            present(svc, animated: true, completion: nil)
        } else {
            let port : PDFViewer = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "PDFViewer") as! PDFViewer
            port.strUrl = self.OtherContactorProfileVview.Result.CertificateList[index].CertificateFileLink
            self.navigationController?.pushViewController(port, animated: true)

        }

Ответ 9

0

Инфраструктура PDFKit от Apple предоставляет широкий спектр кода, который помогает нам работать с PDF файлами, и одним из наиболее полезных является PDFView - он отображает PDF файлы на экране и позволяет пользователям взаимодействовать с ними.

Чтобы попробовать это, начните с импорта структуры PDFKit:

import PDFKit

Затем добавьте этот код в метод viewDidLoad(), чтобы создать PDFView и заполнить все доступное пространство:

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
Finally, create a URL pointing to a PDF you have in your bundle somewhere (or one in your documents directory), then create a PDFDocument object from that and pass it to the PDF view:

guard let path = Bundle.main.url(forResource: "example", withExtension: "pdf") else { return }

if let document = PDFDocument(url: path) {
    pdfView.document = document
}

Готово!

Ответ 10

Проверьте PDFKit от IOS11

Вот пример контроллера представления, который реализует PDFView из PDFKit. Он отображает PDF из вашего пакета ресурсов.

import UIKit
import PDFKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor.lightGray

        // Add PDFView to view controller.
        let pdfView = PDFView(frame: self.view.bounds)
        pdfView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        self.view.addSubview(pdfView)

        // Fit content in PDFView.
        pdfView.autoScales = true

        // Load Sample.pdf file.
        let fileURL = Bundle.main.url(forResource: "Sample", withExtension: "pdf")
        pdfView.document = PDFDocument(url: fileURL!)
    }

}