iOS4 SDK - Opening PDF’s in iBooks

For as simple as opening PDF’s in iBooks for iPhone and iPad I had some issues.  Here is a short guide to do just that, open PDF’s from your application into iBooks.  This demo will be using the iPhone, although I don’t think there will be much difference on iPhone or iPad.

First of all we will be using the UIKit Framework, this is generally already included into all headers you create. We will be using the UIDocumentInteractionController Class

UIDocumentInteractionController Documentation

First of all you will need to create a NSURL object like so:

NSURL *url = [NSURL fileURLWithPath:@”Some File URL”];

Next is what took me a while to figure out, the fact that the UIDocumentInteractionController object is autoreleased object.  Thus once you leave the code block you create it in, it will be released and crash your application.

So to get around this I use the object as a property, and release it from memory at a later point.

docController = [UIDocumentInteractionController interactionControllerWithURL:url];

docController.delegate = self;

[docController retain];

BOOL isValid = [docController presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES];

Using the presentOpenInMenuFromRect will return whether there is a valid application that can open the file.  If there isn’t it will return False.  In this case a PDF can be opened by iBooks, I add some extra validation to display an error message to the user if the file cannot be opened as expected.  

In short this code listed will open an UIActionSheet with the iBooks selection, but if the file is not valid nothing will happen.

The following delegate methods will need to be implemented:

- (void)documentInteractionController:(UIDocumentInteractionController *)controller willBeginSendingToApplication:(NSString *)application

- (void)documentInteractionController:(UIDocumentInteractionController *)controller didEndSendingToApplication:(NSString *)application

- (void)documentInteractionControllerDidDismissOpenInMenu:(UIDocumentInteractionController *)controller

Any questions, comments, or anything I missed please post a comment and let me know.

  1. localbusinessapps reblogged this from andycodes
  2. kandroidsi reblogged this from andycodes
  3. aceisbored reblogged this from andycodes
  4. jacksonfdam reblogged this from andycodes
  5. walpage reblogged this from andycodes
  6. sitdh reblogged this from andycodes
  7. roothybrid7 reblogged this from andycodes
  8. hector99 reblogged this from andycodes
  9. brandontreb reblogged this from andycodes
  10. andycodes posted this