Open PDF Documents in iOS

A document interaction controller provides in-app support for managing user interactions with files in the local system. In this tutorial we will open a PDF document with an external application.

Open Xcode and create a new Single View Application. For product name, use openPDFDocument and then fill out the Organization Name, Company Identifier and Class Prefix fields with your customary values. Make sure only iPhone is selected in Devices, and that the Use Storyboards checkbox is deselected and Use Automatic Reference Counting checkbox is selected.

First, Let's create our User Interface. Go to ViewController.xib. Drag a Button to the main View. Doubleclick the button and give it a name of "Open PDF". The main View should look like this.

Select the assistant editor and open ViewController.m. Ctrl and drag from the button to the interface section and create a IBAction method.

Change the interface line in ViewController.m to make our ViewController a delegate for the UIDocumentInteraction Controller.

@interface ViewController : UIViewController <UIDocumentInteractionControllerDelegate>

Add a UIDocumentInteractionController property

@property (nonatomic, strong) UIDocumentInteractionController *controller;

Next, implement the openPDF IBAction method

- (IBAction)openPDF:(id)sender 
NSURL *URL = [[NSBundle mainBundle] URLForResource:@"MobileHIG" withExtension:@"pdf"];
if (URL)
self.controller = [UIDocumentInteractionController interactionControllerWithURL:URL];
self.controller.delegate = self;

// Present "Open In Menu"
[self.controller presentOpenInMenuFromRect:[sender frame] inView:self.view animated:YES];

We load a sample PDF document from our main Bundle and we initialize our UIDocumentInteractionController with this PDF. Next, we display our "Open in" screen to select an external application.

Build and Run this project on Device, because iOS will look for apps that are able to open documents (for example Evernote or Dropbox).

You can download the source code of the OpenPDFDocument at the ioscreator repository on github.