Create UIDocumentInteractionController in swift


How to create UIDocumentInteractionController in swift

Introduction to UIDocumentInteractionController Swift:

In this post we will learn how to create UIDocumentInteractionController in Swift language. We will create an example app to learn how to use UIDocumentInteractionController in swift. According to Apple docs, UIDocumentInteractionController is a viewcontroller that previews, open, or print files whose file format cannot be handled directly by your app. In short, UIDocumentInteractioncontroller allows us (developers) to open different files using other apps installed on iPhone or iPad device.

You can check objective C version for UIDocumentInteractionController from below link

How to create UIDocumentInteractionController in ObjectiveC

Implementation for UIDocumentInteractionController in swift:

Create a new project and select single view application from app templates and name it “UiDocumentController-Swift”. Change your Language from objective C to swift.

Change project language to swift

Press Next and then select location for your project where you want to save the project, press create to create your project.

Open ViewController.swift file. Now we will create variable for UIDocumentInteractionController.

 



Open your Main.storyBoard and drag UIButton to it. It’s time to create an IBAction for our button so that we can open UIDocumentInteractionController on pressing it.

   


Connect your button dragged in last step on Main.storyBoard with your IBAction to UIButtonTouchUpInside event.

Open ViewController.swift file and now we will write code to present UIDocumentInteractionController to the user.



  

In above code, first we get file url which we want to share using UIDocumentInteractionController (in our case its an image place locally in our project). After we get file path we created our UIDocumentInteractionController by using init method and pass the file url to it. Lastly, we user presentOptionsMenuFromRect method to show UIDocumentInteractionController to the user.
PresentOptionMenuFromRect take three parameters
1) frame: from where we want to the menu 
2) inView: in which we want to show the UIDocumentInteractionController
3) animated: wether you want to present your UIDocumentInteractionController animated or not

Complete Code for UIDocumentInteractionController:

 


Where to go from here:

In this post your leaned. how to create UIDocumentInteractionController in swift language. We created example app that creates UIDocumentInteractionController using swift language and showcased how can we create and use UIDocumentInteractionController using swift language.
If you are looking for Objective C Version of the UIDocumentInteractionController you can check it from here

 UIDocumentInteractionController – ObjectiveC