UIDocumentInteractionControllerを使ってOption Menuを表示する [UIDocumentInteractionController] [share] [swift2.3] [swift3]
前回はInstagramへの投稿をやりましたが、今回は何でもアリのUIDocumentInteractionControllerを使用したOption Menuを表示する方法をメモしておきます。
こんなやつです。
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には開きたいファイルの種類を指定します。
詳細は以下をご参考ください。
3. interactionController: UIDocumentInteractionControllerを宣言
このままだとエラーが出てしまいます。
スコープが広いところに以下の宣言を記載します。
var interactionController : UIDocumentInteractionController?
以上で何でもアリのOptionMenuが表示されると思います。
URLスキームを使用したファイルの共有方法については以下のリンクを参照してみてください。