MILLEN BOX

音楽好きの組み込みソフトエンジニアによるプログラミング(主にiOSアプリ開発)の勉強の記録

UIDocumentInteractionControllerを使ってOption Menuを表示する [UIDocumentInteractionController] [share] [swift2.3] [swift3]

前回はInstagramへの投稿をやりましたが、今回は何でもアリのUIDocumentInteractionControllerを使用したOption Menuを表示する方法をメモしておきます。

こんなやつです。
f:id:anthrgrnwrld:20161014001005p:plain

Githubは以下です。

▶︎GitHub - anthrgrnwrld/drawWithExpand

1. UIDocumentInteractionControllerDelegate

ViewControllerにUIDocumentInteractionControllerDelegateを追記します。

class ViewController: UIViewController, UIScrollViewDelegate, UIDocumentInteractionControllerDelegate {
    ...
}

2. IBAction内に以下のコードを記述

  • swift2.3
    @IBAction func pressOpenIn(sender: AnyObject) {
        let imageData = UIImageJPEGRepresentation(self.canvasView.image!, 1.0)
        let tmpDirectoryPath = NSTemporaryDirectory()   //tmpディレクトリを取得
        let imageName = "tmp.jpg"
        let imagePath = tmpDirectoryPath + imageName
        let imageURLForOptionMenu = NSURL(fileURLWithPath: imagePath)
        
        do {
            try imageData?.writeToURL(imageURLForOptionMenu, options: .AtomicWrite)
        } catch {
            fatalError("can't save image to tmp directory.")
        }
        
        interactionController = UIDocumentInteractionController(URL: imageURLForOptionMenu)
        interactionController?.delegate = self
        self.interactionController?.UTI = "public.jpg"
        interactionController?.presentOptionsMenuFromRect(self.view.frame, inView: self.view, animated: true)
    }
  • swift3
    @IBAction func pressOpenIn(_ sender: AnyObject) {
        //print("\(NSStringFromClass(self.classForCoder)).\(#function) is called!")
        
        let imageData = UIImageJPEGRepresentation(self.canvasView.image!, 1.0)
        let tmpDirectoryPath = NSTemporaryDirectory()   //tmpディレクトリを取得
        let imageName = "tmp.jpg"
        let imagePath = tmpDirectoryPath + imageName
        imageURLForOptionMenu = URL(fileURLWithPath: imagePath)
        
        do {
            try imageData?.write(to: imageURLForOptionMenu!, options: .atomic)
        } catch {
            fatalError("can't save image to tmp directory.")
        }
        
        interactionController = UIDocumentInteractionController(url: imageURLForOptionMenu!)
        interactionController?.delegate = self
        self.interactionController?.uti = "public.jpg"
        interactionController?.presentOptionsMenu(from: self.view.frame, in: self.view, animated: true)
        
    }
    

utiには開きたいファイルの種類を指定します。
詳細は以下をご参考ください。

developer.apple.com

3. interactionController: UIDocumentInteractionControllerを宣言

このままだとエラーが出てしまいます。
スコープが広いところに以下の宣言を記載します。

var interactionController : UIDocumentInteractionController?

以上で何でもアリのOptionMenuが表示されると思います。

URLスキームを使用したファイルの共有方法については以下のリンクを参照してみてください。

anthrgrnwrld.hatenablog.com