One of the common tasks that an iOS developer has to do is to import or export documents from his iOS application. For example, suppose you are developing a document reader and you want to allow the user to import documents into your application so that it can be read offline. Also, your reader might also support the exporting of documents so that other applications can make use of the document.
In this article, I will walk you through the different techniques you can employ to allow documents to be imported or exported from your iOS application.
Creating the Project
As usual, I will be using an example to illustrate the various techniques discussed in this article. Using Xcode, create a new View-based Application (iPhone) project and name it OfflineReader.Double-click on the OfflineReaderViewController.xib to open it in Interface Builder and populate it with the following views (see Figure 1):
- WebView
In the Attributes Inspector window for the WebView, ensure that you check the “Scales Page to Fit” item.
In the OfflineReaderViewController.xib file, add in the following statements in bold:
#import <UIKit/UIKit.h> @interface OfflineReaderViewController : UIViewController <UIDocumentInteractionControllerDelegate> { IBOutlet UIWebView *webView; } -(void)openDocumentIn; -(void)handleDocumentOpenURL:(NSURL *)url; -(void)displayAlert:(NSString *) str; -(void)loadFileFromDocumentsFolder:(NSString *) filename; -(void)listFilesFromDocumentsFolder; - (IBAction) btnDisplayFiles; @end
Drag and drop two files into the Resources folder of the project (see Figure 3). In this example, I have a PDF file named “Courses for Q2 2011.pdf” and an image file named icon.jpg.
In the OfflineReader-Info.plist file, set the “Icon file” key to “icon.jpg”.
So now you have an iPhone application with the icon set. It also has a PDF document in the Resources folder.
Exporting Documents
The first thing you will learn is how to export a document from your application. For example, in the Mail application on your iPhone, when you received a PDF file, you can either tap on the icon (see Figure 4) to view the document within the Mail application, or tap and hold onto the icon.If you do the latter, an action sheet would be displayed (see Figure 5). You can tap on the “Open in...” button to see a list of applications that your document can be exported to.
In my case, it will display the list as shown in Figure 6.
So let’s now modify our application so that we can export the PDF document in the Resources project to an external application.
First, declare a variable of type UIDocumentInteractionController in the OfflineReaderViewController.m file:
#import "OfflineReaderViewController.h" @implementation OfflineReaderViewController UIDocumentInteractionController *documentController;
Next, define the following methods:
-(void)openDocumentIn { NSString * filePath = [[NSBundle mainBundle] pathForResource:@"Courses for Q2 2011" ofType:@"pdf"]; documentController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:filePath]]; documentController.delegate = self; [documentController retain]; documentController.UTI = @"com.adobe.pdf"; [documentController presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES]; } -(void)documentInteractionController:(UIDocumentInteractionController *)controller willBeginSendingToApplication:(NSString *)application { } -(void)documentInteractionController:(UIDocumentInteractionController *)controller didEndSendingToApplication:(NSString *)application { } -(void)documentInteractionControllerDidDismissOpenInMenu: (UIDocumentInteractionController *)controller { }
The other three methods are the methods defined in the UIDocumentInteractionControllerDelegate protocol. They are fired when the documentController object is being invoked. For this example, you don’t really need to code anything within these methods.
Finally, in the viewDidLoad method, add the following statement:
- (void)viewDidLoad { [super viewDidLoad]; [self openDocumentIn]; }
If you select iBooks, the PDF document will appear in iBooks (see Figure 8).
File Sharing
The previous section showed how you can export a document to an external application. What about the other way round – importing a document into your application? In iOS, there are two ways to get files into your application:- File Sharing through iTunes
- Through exchanges between applications (like the one you just saw in the previous section)
Press Command-R to redeploy the application onto the real device again. Launch iTunes and select the device name, followed by the Apps tab. Figure 10 shows that the OfflineReader application now appears under the File Sharing section.
To copy a file into the application, simply drag and drop it into the rectangle labeled OfflineReader Documents. Figure 11 shows that I have copied a PDF document into the application. All documents copied will reside in the Documents folder of your application.
If you want to extract the files from the application and save it locally onto your computer, select the file(s) and click the Save to… button.
Now, to prove that the files are really copied into the Documents folder of your application, add the following code to the OfflineReaderViewController.m file:
-(void) displayAlert:(NSString *) str { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert" message:str delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; [alert release]; } - (void)handleDocumentOpenURL:(NSURL *)url { NSURLRequest *requestObj = [NSURLRequest requestWithURL:url]; [webView setUserInteractionEnabled:YES]; [webView loadRequest:requestObj]; } -(void)loadFileFromDocumentsFolder:(NSString *) filename { //---get the path of the Documents folder--- NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *filePath = [documentsDirectory stringByAppendingPathComponent:filename]; NSURL *fileUrl = [NSURL fileURLWithPath:filePath]; [self handleDocumentOpenURL:fileUrl]; } -(void)listFilesFromDocumentsFolder { //---get the path of the Documents folder--- NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSFileManager *manager = [NSFileManager defaultManager]; NSArray *fileList = [manager contentsOfDirectoryAtPath:documentsDirectory error:nil]; NSMutableString *filesStr = [NSMutableString stringWithString:@"Files in Documents folder \n"]; for (NSString *s in fileList){ [filesStr appendFormat:@"%@ \n", s]; } [self displayAlert:filesStr]; [self loadFileFromDocumentsFolder:@"0470918020.pdf"]; } - (IBAction) btnDisplayFiles { [self listFilesFromDocumentsFolder]; }
Press Command-R to deploy the application on the device again. Tapping the Display files in Documents button will display the filename and at the same time load the PDF document in the WebView (see Figure 12), proving that the file was transferred into the application successfully.
Importing Documents
The second method to transfer documents into an application is through another application (as seen in the first section of this article). In the beginning of this article, you saw how a PDF document in your application can be transferred to the iBooks application for viewing. This time round, you will learn how a document can be transferred into your own application.For a start, you shall modify the application to accept PDF documents. What you need to do is to get your application to register with the iOS that it is able to accept PDF document. To do this, you need to modify the OfflineReader-Info.plist file.
Add the new CFBundleDocumentTypes key as shown in Figure 13.
Note the following:
- The CFBundleDocumentTypes key is of type Array. It contains an array of dictionaries describing the types of documents supported by your application.
- Item 0 is of type Dictionary.
- The CFBundleTypeName key specifies the abstract name for the specified document type.
- The LSHandlerRank key specifies whether the application is the owner (creator of this file type), Alternate (secondary viewer of this file type), None, or Default.
- The CFBundleTypeRole key specifies the application’s role with respect to the type - Editor, Viewer, Shell, or None.
- The LSItemContentTypes key is of type Array. It contains an array of UTIs specifying the file type.
When a PDF document is passed into the application, the application will fire a particular method – application:openURL:sourceApplication:annotation:. This method must be implemented in the application delegate.
Hence, add the following in the OfflineReaderAppDelegate.m file:
#import "OfflineReaderAppDelegate.h" #import "OfflineReaderViewController.h" @implementation OfflineReaderAppDelegate @synthesize window; @synthesize viewController; -(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation { if (url != nil && [url isFileURL]) { [self.viewController handleDocumentOpenURL:url]; } return YES; }
To see the URL of an imported document, add the following statement to the handleDocumentOpenURL: method:
- (void)handleDocumentOpenURL:(NSURL *)url { [self displayAlert:[url absoluteString]]; NSURLRequest *requestObj = [NSURLRequest requestWithURL:url]; [webView setUserInteractionEnabled:YES]; [webView loadRequest:requestObj]; }
When the document is opened in OfflineReader, you will see the path of the document as shown in Figure 15.
Importing Self-Defined Documents
The previous section showed how to import well-known document types, such as PDF. What happens if you want to import your own self-defined document types? For example, you are writing a Sudoku game and wanted to implement your own file format for saving the state of a Sudoku game. In this case, your file might have the .sdk extension, which is only used by your application.
To ensure that your application can handle files with the .sdk extension, you will add the keys as shown in Figure 16 to the OfflineReader-Info.plist file.
Note that you added another key to the CFBundleDocumentTypes array. You set the LSItemContentTypes to a unique value, using the reverse domain name of your company and the type you are defining. Since this is a self-defined content type, you have to define it using the UTExportedTypeDeclarations key.
Note: For more information on UTI, refer to Apple’s documentations – “Introduction to Uniform Type Identifiers Overview”.
Press Command-R to test the application on a real device again. This time round, if your email contains a document of extension .sdk, you will see the icon of your application displayed next to the document name (see Figure 17). When you tap on the document name, you will see a list of options to open your documents with.
没有评论:
发表评论