Skip to content

Instantly share code, notes, and snippets.

@Enchan1207
Created December 21, 2022 14:28
Show Gist options
  • Save Enchan1207/21a20790212695f862609fd8b980d30b to your computer and use it in GitHub Desktop.
Save Enchan1207/21a20790212695f862609fd8b980d30b to your computer and use it in GitHub Desktop.
DocumentPickerを使用したPDFビューア
//
// ViewController.swift
// PDFEx
//
// Created by EnchantCode on 2020/12/26.
//
import UIKit
import PDFKit
import UniformTypeIdentifiers
import MobileCoreServices
class ViewController: UIViewController {
/// PDFビュー
@IBOutlet weak var pdfView: PDFView! {
didSet {
pdfView.autoScales = true
pdfView.usePageViewController(true)
pdfView.displayDirection = .horizontal
}
}
/// サムネビュー
@IBOutlet weak var pdfThumbView: PDFThumbnailView! {
didSet {
pdfThumbView.layoutMode = .horizontal
}
}
/// ファイルピッカー
let picker: UIDocumentPickerViewController = .init(forOpeningContentTypes: [.pdf])
/// 現在表示しているドキュメント
var pdfDocument: PDFDocument?
override func viewDidLoad() {
super.viewDidLoad()
// ピッカー初期設定
picker.delegate = self
picker.allowsMultipleSelection = false
}
@IBAction func onTapFolderButton(_ sender: Any) {
present(picker, animated: true)
}
}
extension ViewController: UIDocumentPickerDelegate {
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
// ファイルパスを取得して開き、
guard let documentURL = urls.first, documentURL.startAccessingSecurityScopedResource() else {return}
pdfDocument = PDFDocument(url: documentURL)
documentURL.stopAccessingSecurityScopedResource()
// PDFViewに設定
pdfView.document = pdfDocument
pdfThumbView.pdfView = pdfView
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment