4
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Swift3とAlamofireでPDFファイルをダウンロードしてReaderで表示する

Posted at

PDFデータをダウンロードしてきて、ローカルに保持しておくサンプルです。

ViewControllerにちょっと書いてみての動作確認になります。

ユーザ作成でなく、バックアップにも含めたいので、Library/ディレクトリに入れます。

ViewController.swift
override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        let destination: DownloadRequest.DownloadFileDestination = { _, _ in
            let documentsURL = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask)[0]
            let fileURL = documentsURL.appendingPathComponent("test.pdf")
            return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
        }
        
        Alamofire.download("http://cdn.oreillystatic.com/oreilly/booksamplers/9781491908693_sampler.pdf", to: destination).response { response in
            print(response)
            if response.error == nil, let pdfPath = response.destinationURL?.path {
                print("pdfPath::::\(pdfPath)")
                let document = ReaderDocument(filePath: pdfPath, password: nil)
                if let document = document {
                    if let readerVC = ReaderViewController(readerDocument: document) {
                        readerVC.delegate = self
                        readerVC.transitioningDelegate = self
                        readerVC.modalPresentationStyle = .fullScreen
                        self.present(readerVC, animated: false, completion: nil)
                    }
                }
            }
        }
    }

ReaderViewControllerDelegateは必要なので追記

ViewController.swift
extension ViewController: ReaderViewControllerDelegate {
    func dismiss(_ viewController: ReaderViewController!) {
        self.dismiss(animated: true, completion: nil)
    }
}

Alamofire
https://github.com/Alamofire/Alamofire#downloading-data-to-a-file

PDFViewerはこちらを使います。
https://github.com/vfr/Reader

4
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?