Created
December 21, 2022 14:28
-
-
Save Enchan1207/21a20790212695f862609fd8b980d30b to your computer and use it in GitHub Desktop.
DocumentPickerを使用したPDFビューア
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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