Amarronの日記

iOSやMac、Web系の記事を書きます。

Swift PDF Download Export 実装方法

f:id:Amarron:20151129162938p:plain:w350

概要

PDFのDownload

  • NSURLSessionDownloadDelegateを利用してダウンロードします
  • 以下のプログラムは「download」ボタン押下で、指定したURLからPDFをダウンロードするよう書いてあります
// NSURLSessionDownloadDelegateを追加
class YourClass:UIViewController, NSURLSessionDownloadDelegate {
    // PDF保存先のディレクトリを定義
    let dir = NSSearchPathForDirectoriesInDomains(
        .DocumentDirectory,
        .UserDomainMask, true)

    @IBAction func download(sender: AnyObject) {
        // ダウンロードしたいPDFのURLを指定
        let url = NSURL(string: "http://www.indire.it/wp-content/uploads/2015/08/pdf-sample.pdf")
        
        let config = NSURLSessionConfiguration.defaultSessionConfiguration()
        let session = NSURLSession(configuration: config,
            delegate: self,
            delegateQueue: NSOperationQueue.mainQueue())
        // PDFのダウンロード
        let task = session.downloadTaskWithURL(url!)
        task.resume()
    }
    
    // MARK: - NSURLSessionDownloadDelegate
    func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL){
        let data = NSData(contentsOfURL: location)!
        if data.length > 0 {
            let path =
            NSURL(fileURLWithPath: self.dir[0]).URLByAppendingPathComponent("ファイル名.pdf").path
            // PDFの書込み
            data.writeToFile(path!, atomically: true)
        }
    }
    
    func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
        if error == nil{
            session.finishTasksAndInvalidate()
        } else {
            session.invalidateAndCancel()
        }
    }
}

参考:SwiftでPDFをDL、保存して良さ気な見た目で表示しよう (分かりやすいのとプログレスバーがステキです)

PDFのExport

  • 「UIDocumentInteractionController」を使って出力します
  • 「UIDocumentInteractionController」は、メソッド内に書くとメモリが開放されてクラッシュするのでクラス変数で定義した方が良いと思います
  • 以下のプログラムは「export」ボタン押下で、指定したURLからPDFをダウンロードするよう書いてあります
    • プロジェクト内のファイルを出力したい場合、「NSBundle.mainBundle().URLForResource().path」で出力できます
class YourClass:UIViewController {
    // ※クラス変数で定義(メソッド内の場合、メモリが解放されてしまう)
    var dic:UIDocumentInteractionController? 

    @IBAction func export(sender: AnyObject) {
         // プロジェクト内のファイルを指定したい時
         // if let path = NSBundle.mainBundle().URLForResource("ファイル名", withExtension: "pdf").path! {
        if let path = NSURL(fileURLWithPath: self.dir[0]).URLByAppendingPathComponent("ファイル名.pdf").path {
            dic = UIDocumentInteractionController(URL: NSURL(fileURLWithPath: path))
            dic?.presentOpenInMenuFromRect(CGRectZero, inView: self.view, animated: true)
        }
    }
}

サンプルコード

サンプルコードを作りました。ご参考までに。

github.com

機能

  • PDFのダウンロード
  • ダウンロードしたPDFの一覧表示
  • ダウンロードしたPDFの削除
  • PDFをエクスポート

使い方

  1. ダウンロードしたいPDFのURLをテキストエリアにペースト
  2. ダウンロードボタン押下でPDFをダウンロード
  3. テーブルにダウンロードしたPDFファイル名が追加されて表示
  4. エクスポートしたいファイル名を選択するとエクスポート先が表示
  5. エクスポート先でPDFが表示
  6. ダウンロードしたPDFを削除したい場合は対象のファイル名を右へスワイプ

f:id:Amarron:20151129163036j:plain:w350 f:id:Amarron:20151129163047j:plain:w350