Home > Articles > Mobile Application Development & Programming

  • Print
  • + Share This
This chapter is from the book

The Document Interaction Controller

The UIDocumentInteractionController class allows applications to present a menu of options to users, allowing them to use document files in a variety of ways. With this class, users can take advantage of

  • iOS application-to-application document sharing (i.e., “open this document in...some app”)
  • Document preview using iOS’s built-in QuickLook technology
  • Copying documents to the pasteboard or printing them

The controller is presented as a small menu, which allows users to specify how they want to interact with the given document. Figure 16-4 shows presentations on the iPad and iPhone.

Figure 16-4

Figure 16-4. The UIDocumentInteractionController shown in its options style for iPad (left) and iPhone (right).

The controller offers two basic menu styles. The “open” style offers only “open in” choices, using the menu space to provide as many destination choices as possible. The “options” style (refer to Figure 16-4) provides a list of all interaction options including open-in, quick-look, and any supported actions. Figure 16-5 shows the basic options available via these controllers.

Creating Document Interaction Controller Instances

Each document interaction controller is created to present options for a file, typically in the user’s Documents folder. You supply a URL pointing to the file and present the controller, typically from a bar button. The bar button presentation style works across platforms and simplifies coding, even though the iPhone implementation scrolls the controller view up from the bottom of the screen as an action sheet.

As a rule, I use a local instance variable to hold onto any current controllers and popovers, dismissing them before introducing any new choice items. Keep that in mind as you read through this section and the ones that follow it.

Figure 16-5

Figure 16-5. The document interaction controller provides access from your application to a variety of system services, as well as to other applications that support editing and viewing a document.

Thank you, Omni Group, for providing a copy of OmniGraffle to help build this diagram.

The following snippets show how to create and present both styles of controllers. In each case, any previous controller is dismissed, a new controller created, and the delegate assigned to the primary view controller. The presentation method determine whether the controller is shown as an options menu (presentOptionsMenuFromBarButtonItem:animated:) or as an open-in menu (presentOpenInMenuFromBarButtonItem:animated:).

- (void) options: (UIBarButtonItem *) bbi

{

    if (dic)

        [dic dismissMenuAnimated:NO];



    dic = [UIDocumentInteractionController

        interactionControllerWithURL:

            [NSURL fileURLWithPath:path]];

    dic.delegate = self;



    [dic presentOptionsMenuFromBarButtonItem:bbi animated:YES];

}



- (void) open: (UIBarButtonItem *) bbi

{

    if (dic)

        [dic dismissMenuAnimated:NO];



    dic = [UIDocumentInteractionController

        interactionControllerWithURL:

            [NSURL fileURLWithPath:path]];

    dic.delegate = self;



    [dic presentOpenInMenuFromBarButtonItem:bbi animated:YES];

}

I always implement dismissal callbacks in order to round out my local instance variable approach.

- (void) documentInteractionControllerDidDismissOpenInMenu:

     (UIDocumentInteractionController *) controller

    {  dic = nil; }



- (void) documentInteractionControllerDidDismissOptionsMenu:

    (UIDocumentInteractionController *) controller

    {  dic = nil; }

Document Interaction Controller Properties

Each document interaction controller offers a number of properties, which can be used in your delegate callbacks:

  • The URL property allows you to query the controller for the file it is servicing. This is the same URL you pass when creating the controller.
  • The UTI property is used to determine which apps can open the document. It uses the automatic routines discussed earlier in the chapter to find the most preferred UTI match based on the file name and metadata, although you can override this in code to set the property manually.
  • The name property provides the last path component of the URL, offering a quick way to provide a user-interpretable name without having to manually strip the URL yourself.
  • Use the icons property to retrieve an icon for the file type. Applications that declare support for certain file types provide image links in their declaration (as you’ll see shortly, in the discussion about declaring file support). These images correspond to the values stored for the kUTTypeIconFileKey key, as discussed earlier in this chapter.
  • The annotation property provides a way to pass custom data along with a file to any application that will open the file. There are no standards for using this property, although the item must be set to some top-level property list object, namely dictionaries, arrays, data, strings, numbers, and dates. Because there are no community standards yet, use of this property tends to be minimal except where developers use the information across their own suite of published apps.

Providing Document Quick Look Support

Add Quick Look support to your apps by providing a trio of delegate callbacks. In these methods, you declare which view controller will be used to present the preview, which view will host it, and the frame for the preview size. You may have occasional compelling reasons to use a child view controller with limited screen presence on the iPad (such as in a split view, with the preview in just one portion), but for the iPhone, there’s almost never any reason not to allow the preview to take over the entire screen.

#pragma mark QuickLook

- (UIViewController *)

    documentInteractionControllerViewControllerForPreview:

       (UIDocumentInteractionController *)controller

{

    return self;

}



- (UIView *)

    documentInteractionControllerViewForPreview:

    (UIDocumentInteractionController *)controller

{

    return self.view;

}



- (CGRect)

    documentInteractionControllerRectForPreview:

    (UIDocumentInteractionController *)controller

{

    return self.view.frame;

}

Providing Printer and Copy Support

The interaction controller class currently offers two possible actions: namely, printing and copying. These actions are sent as selector parameters, namely copy: and paste:, to a pair of delegate methods. The first method specifies whether each action (and any other future action that Apple might support) can be performed. If so, it can be added to the actions menu. If not, that item is skipped. This method is called by the controller as it builds the menu and before it’s presented.

In the following snippet, each action request is handled separately. In the case of copying, the file’s size is checked, limiting copies to under 5MB. This approach assumes the application will be pasting actual data, rather than a URL pointing to the document. For the later case, you might simply return YES after checking for the file’s existence rather than calculating its size.

The print action here is set to be contingent on whether printing is available. You can create a pseudo printer for your system in the Simulator by choosing File > Open Printer Simulator. I personally use Ecamm’s $20 Printopia product (www.ecamm.com/mac/printopia/) to enable AirPrinting to my normal Brother printer. It acts as an AirPrint server and then redirects any print requests to my normally non-AirPrint–enabled hardware. Printopia also allows me to “print” to DropBox, which is also handy, especially for saving paper.

- (BOOL) documentInteractionController:

    (UIDocumentInteractionController *)controller

    canPerformAction:(SEL)action

{

    if (action == @selector(copy:))

    {

        // Copy only items under 5MB

        long long fileSize =

            [[NSFileManager defaultManager]

                attributesOfItemAtPath:path error:nil].fileSize;

        return (fileSize < 5 * 1024 * 1024);

    }



    if (action == @selector(print:))

    {

        return [UIPrintInteractionController isPrintingAvailable];

    }



    return YES;

}

The actual copying and printing is performed in a second delegate callback. In this method, once again, the requested action is checked before performing any task. This application sample manages images, using the pasteboard’s image property to perform the copy action. As with the previous method, you’ll need to adapt this to whatever data you’re actually working with.

On the printing end of things, the printer is first checked to see if the item can be printed. If not, it logs an error and returns. Otherwise, it chooses the appropriate print controller presentation on a per-platform basis and presents it. All further printing control is handled through the UIPrintInteractionController class. If you want to act as the print controller’s delegate, there is a full suite of callbacks that you can implement. The callbacks let you know when the print job has started and stopped. For the most part, I just let it run in its default and let these things be as they may.

- (BOOL) documentInteractionController:

    (UIDocumentInteractionController *)controller

    performAction:(SEL)action

{

    if (action == @selector(copy:))

    {

        // Copy the image to the pasteboard

        UIImage *image = [UIImage imageWithContentsOfFile:path];

        [UIPasteboard generalPasteboard].image = image;

        return YES;

    }



    if (action == @selector(print:))

    {

        // Check if the item can be printed

        if (![UIPrintInteractionController

            canPrintURL:controller.URL])

        {

            NSLog(@"Item is not printable: %@", controller.URL);

            return NO;

        }



        [UIPrintInteractionController

            sharedPrintController].printingItem = controller.URL;

        if (IS_IPAD)

            [[UIPrintInteractionController sharedPrintController]

                presentFromBarButtonItem:

                    self.navigationItem.rightBarButtonItem

                animated:YES completionHandler:nil];

        else

            [[UIPrintInteractionController sharedPrintController]

                presentAnimated:YES completionHandler:nil];

        }

        return YES;

    }



    return YES;

}
  • + Share This
  • 🔖 Save To Your Account