Go: File sharing between iOS programs

Source: Internet
Author: User

Original

system-declared Uniform Type Identifiers

One of the common tasks that an IOS developer have to do are to import or export documents from his iOS application. For example, suppose-developing a document reader and you want-to-allow the user-import documents into your app Lication so the it can be read offline. Also, your reader might Also, the exporting of documents so, and applications can make use of the document.

In this article, I'll walk you through the different techniques your can employ to allow documents to be imported or expo RTed from your IOS application.

Creating the Project

As usual, I'll be using a 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 Vie WS (See Figure 1):

    • WebView
    • Round Rect Button


      Figure 1. Populating the View window

      In the Attributes Inspector window for the WebView, ensure so 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

      Interface Builder, connect the outlet and action to the WebView and Button views. Right-clicking on the File's Owner in the Offlinereaderviewcontroller.xib window should now reveal the connections as show N in Figure 2.


      Figure 2. Confirmation the connections of the action and outlet

      Drag and drop both files into the Resources folder of the project (see Figure 3). In this example, I has a PDF file named "Courses for Q2 2011.pdf" and an image file named Icon.jpg.


      Figure 3. Adding both files to the Resources folder of the project

      In the Offlinereader-info.plist file, set the "Icon file" key to "icon.jpg".

      So are now a iPhone application with the icon set. It also have a PDF document in the Resources folder.

      Exporting Documents

      The first thing you'll learn is what to export a document from your application. For example, with the Mail application on your IPhone, when you received a PDF file, you can either tap on the icon (see Fig Ure 4) To view the document within the Mail application, or tap and hold onto the icon.


      Figure 4. A PDF document in Mail

      If you do the latter, an action sheet would is displayed (see Figure 5). You can tap on the ' Open in ... ' button to see a list of applications that your document can is exported to.


      Figure 5. Viewing your application in an external application

      In my case, it would display the list as shown in Figure 6.


      Figure 6. A List of applications able to handle your document

      So let's now modify our application so we can export the PDF document in the Resources project to an external Applica tion.

      First, declare a variable of type Uidocumentinteractioncontroller in the offlinereaderviewcontroller.m file:

      #import "OfflineReaderViewController.h" @implementation Offlinereaderviewcontroller Uidocumentinteractioncontroller *documentcontroller;

      The Uidocumentinteractioncontroller class provides in-app support for providing user interaction with files in your applic ation. In this example, you'll use it for export a document to an external application.

      Next, define the following methods:

      -(void) Opendocumentin {NSString * filePath = [[NSBundle mainbundle] pathforresource:@ "Courses for        Q2 "oftype:@" PDF "]; Documentcontroller = [Uidocumentinteractioncontroller interactioncontrollerwithurl:[nsurl FileURLWithP    Ath:filepath]];    Documentcontroller.delegate = self;    [Documentcontroller retain];    Documentcontroller.uti = @ "Com.adobe.pdf"; [Documentcontroller Presentopeninmenufromrect:cgrectzero INVIEW:SELF.VI EW Animated:yes];}  -(void) Documentinteractioncontroller: (Uidocumentinteractioncontroller *) Controller Willbeginsendingtoappli Cation: (NSString *) application { } -(void) Documentinteractioncontroller: ( Uidocumentinteractioncontroller *) Controller didendsendingtoapplication: (NSString *) application { }&nbsp ;-(void) Documentinteractioncontrollerdiddismissopeninmenu: (UidocumentinteRactioncontroller *) controller { } 

      The Opendocumentin method basically creates the path to point to the PDF document (that's want to export) and then uses It to feeds into the Documentcontroller object. You need to set the UTI (Uniform Type Identifiers) for the Documentcontroller object so, it can help the system find T He appropriate application to open your document. In this case, the it is set to "Com.adobe.pdf", which represents a PDF document. Other common UTIs is "Com.apple.quicktime-movie" (QuickTime Movies), "public.html" (HTML documents), and "Public.jpeg" (J PEG files).

      The other three methods is the methods defined in the Uidocumentinteractioncontrollerdelegate protocol. They was fired when the Documentcontroller object was being invoked. For the 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];}

      Press Command-r to test the application-a real device (the Simulator won ' t work in this case). When the View window was loaded, you'll see a action sheet displaying the list of applications that's you can export your Document to (see Figure 7).


      Figure 7. Exporting PDF document to an external application

      If you select ibooks, the PDF document would appear in IBooks (see Figure 8).


      Figure 8. IBooks showing our PDF document

      File sharing

      The previous section showed how can export a document to an external application. What is the other-the-round–importing a document into your application? In IOS, there is, 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)

      Let ' s discuss the first method first. The first method presents a very easy and direct-to-a-transfer large number of files into or out of a applica tion. In the Offlinereader-info.plist file, add a new key named uifilesharingenabled and check it (see Figure 9).


      Figure 9. Adding a new key to enable file sharing for your application

      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 shows that the Offlinereader application now Appears under the File sharing section.


      Figure Ten. The application is now listed under the File sharing section of ITunes

      To copy a file into the application, simply drag and drop it into the rectangle labeled Offlinereader Documents. Figure one shows that I had copied a PDF document into the application. All documents copied would reside in the Documents folder of your application.


      Figure one by one . Copying a document into the 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 the files is really copied into the Documents folder of your application, add the following code to th E offlinereaderviewcontroller.m File:

      -(void) DisplayAlert: (NSString *) str {Uialertview *alert = [[Uialertview alloc] initwithtitle:@ "alert" Message:str delegate:self Cancelbut    tontitle:@ "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---NSA     Rray *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 = NS     Searchpathfordirectoriesindomains (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]; }

      Here, the Displayalert:method are simply a helper method to display an Alert View on the screen. The Handledocumentopenurl:method takes in a Nsurl object and loads the WebView with its content. The Loadfilefromdocumentsfolder:method takes in a filename and converts it path into a Nsurl object. The Listfilesfromdocumentsfolder method displays all the files and folders contained within the Documents folder of the AP Plication. Here, I had hardcoded it to display the PDF document named "0470918020.pdf" (which was what I had copied earlier).

      Press Command-r to deploy the application on the device again. Tapping the display files in Documents button would Display the filename and at the same time load the PDF document in the WebView (see figure), proving the file is transferred into the application successfully.


      Figure . Displaying the files in the Documents folder and loading the PDF document

      Importing Documents

      The second method to transfer documents into an application are through another application (as seen in the first section O F this article). In the beginning of this article, what do you saw? A PDF document in your application can is transferred to the IBooks Applicat Ion for viewing. This time round, you'll learn how a document can is transferred into your own application.

      For a start, you shall modify the application to accept PDF documents. What's need to does is to get your application to register with the IOS that it's able to accept PDF document. Need to modify the Offlinereader-info.plist file.

      ADD the new Cfbundledocumenttypes key as shown in Figure 13.


      Figure . Add a new key to support PDF documents

      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 vie Wer 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.

      The above entry in the Offlinereader-info.plist file would register with IOS, the application is capable of handling PD F documents.

      When a PDF document was passed into the application, the application would fire a particular method–application:openurl:so Urceapplication:annotation:. This method must is 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;}

      When a document was passed into your application, it would be copied into a folder called Inbox, located within the document S folder. The URL argument contains the path to the document in the Inbox folder. In the above, once the document was passed in, you'll call the Handledocumentopenurl:method defined in the Offlinereader Viewcontroller class to load the document in the WebView.

      To see the URL of a 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];}

      Press Command-r to deploy the application onto the real device again. This time, if you go back to the same e-mail containing the PDF document and tap and hold for it, you'll find that The option to open the document is in the Offlinereader application (see Figure 14).


      Figure . Your application is capable of handling PDF document

      When the document was opened in Offlinereader, you'll see the path of the document as shown in Figure 15.


      Figure . Confirming the path of the document in the Documents/inbox folder

      Importing self-defined Documents

      The previous section showed what to import well-known document types, such as PDF. What happens if do want to import your own self-defined document types? For example, you is writing a Sudoku game and wanted to implement your own file format for saving the state of a Sudoku g Ame. In this case, your file might has the. SDK extension, which is only used by your application.

      To ensure this your application can handle files with the. sdk extension, you'll add the keys as shown in Figure t He offlinereader-info.plist file.


      Figure . Adding new keys to support self-defined document types

      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 is Defin Ing. Since This was a self-defined content type, you had to define it using the Utexportedtypedeclarations key.

      Note:for more information in 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 e-mail contains a document of extension. SDK, you'll see the icon of your application displayed Next to the document name (see Figure 17). When you tap on the document name, you'll see a list of options to open your documents with.


      Figure . Opening a file of type. SDK

      Summary

      In this article, you are seen the different techniques for handling documents in your application. With this knowledge, you'll be a able to write cool IOS applications It allows them to interact with the outside world!

Go: File sharing between iOS programs

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.