How to input and output data through email in applications

Source: Internet
Author: User
Tags file url

This article can also be found in English

Load attachments in your app!

Many developers want to share their application data via email. This is a convenient method for data transmission between users and between devices-it can even bring you new users.
Fortunately, this is easy to implement in iPhone application development-you only need to go to info. set several keys in plist and process several return functions so that the control system can introduce data through URL to enable the application.
We will explain how these are implemented in this tutorial.
We will begin with the scary bugs project. We started this project in the simple application tutorial and updated it in the file sharing tutorial.
If you do not have this project, you can download it here.

Set your info. plist

We have made a lot of preparations to support email sharing application data-we have written code to save the application data in an independent copy.
So what we need to do next is to set info. plist to let the operating system know that we can handle "scary bug Files ". The specific operation is to register your application for processing specific UTI, and introduce the uti that the system does not know.
In general, uti represents the unique identifier of your file, just like "com. raywenderlich. scarybugs. sbz. A few images of files, such as your public.htm and your public.html, and their own built-in UTI.
Next, we will register the application as "an application that can process the uti generated by ourselves", and then we will inform the operating system of the uti information, for example, the file extension used by it and the MIME type used in email encoding.
Now let's take a look at the specific operations! Open the ScaryBugs-Info.plist and add the following entries:

You can check the meanings of these values in Apple's UTI manual, but pay attention to the following points:

  • The cfbundledocumenttypes entry means that our application supports the/Some UTs as the owner/editor. In our application, it is com. raywenderlich. scarybugs. sbz UTI.

  • The utexportedtypedeclaration entry provides information about com. raywenderlich. scarybugs. sbz, because it is not a common UTI. That is to say, if the suffix of any file is. sbz or its MIME type is application/scarybugs, it belongs to the file type we support.

Believe it or not, setting these keys is all we have to do to let the operating system start to transfer application data suffixed with. sbz. You can send yourself a sample bug for testing.

If you want to open scary bugs, you can press and hold the attachment. If you do this, the scary bugs will be opened. Of course, it will not be loaded here, because we have not added any code. This is what we will do next.

Introduce application data

When an email or another application wants to send a file to your application, you can use application: didfinishlaunchingwitexceptions to use uiapplicationlaunchoptionsurlkey to transmit the URL, or use application: handleopenurl.
To understand when these events occur, you can see an article with charts written by Oliver drobnick that describes how to call these methods.
Now let's start to implement it-this is very simple, because we have done a lot of preparation work.

Add the following changes to scarybugdoc. h:

// After @interface- (BOOL)importFromURL:(NSURL *)importURL;

Add the following code to scarybugdoc. M:

// Add new function- (BOOL)importFromURL:(NSURL *)importURL {    NSData *zippedData = [NSData dataWithContentsOfURL:importURL];    return [self importData:zippedData];    }

Add the following code to rootviewcontroller. h:

// After @interface- (void)handleOpenURL:(NSURL *)url;

Add the following code to rootviewcontroller. M:

// New method- (void)handleOpenURL:(NSURL *)url {    [self.navigationController popToRootViewControllerAnimated:YES];    ScaryBugDoc *newDoc = [[[ScaryBugDoc alloc] init] autorelease];    if ([newDoc importFromURL:url]) {        [self addNewDoc:newDoc];           }}

Finally, add the following code to scarybugsappdelegate. M:

// Add at end of application:didFinishLaunchingWithOptionsNSURL *url = (NSURL *)[launchOptions valueForKey:UIApplicationLaunchOptionsURLKey];if (url != nil && [url isFileURL]) {        [rootController handleOpenURL:url];                } // Add new method-(BOOL) application:(UIApplication *)application handleOpenURL:(NSURL *)url {     RootViewController *rootController = (RootViewController *) [navigationController.viewControllers objectAtIndex:0];    if (url != nil && [url isFileURL]) {        [rootController handleOpenURL:url];                    }         return YES; }

This is not hard to understand, but pay attention to the following points.
First, we add a method in scarybugdoc to introduce the file from the URL. The URL passed to us from the system is actually a copy of the files in the directory of our application. So we use nsdata to read it and pass it to the previously written importdata method.
In rootviewcontroller, we play back to the root View Controller (unless we are somewhere in the Detail View), generate a new file, and introduce the file from the specified URL.
In scarybugsappdelegate, where we can receive the URL we need, if this is a File URL (instead of a queue string, we may have a special tutorial later ), we will notify the Root View Controller that it can be introduced now.
Compile and run your application now. If everything goes well, you should be able to open the attachment of the email and see the bug of the introduced application!

Output Application Data

Introducing data is a difficult part-the output data will be much simpler.
Make the following changes in editbugviewcontroller. h:

// Add to the top of the file#import <MessageUI/MessageUI.h>// Modify EditBugViewController to have two new protocols: UIActionSheetDelegate and [email protected] EditBugViewController : UIViewController <UITextFieldDelegate, RateViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIAlertViewDelegate, UIActionSheetDelegate, MFMailComposeViewControllerDelegate> {

Then, modify editbugviewcontroller. m as follows:

// Replace exportTapped with the following:- (void)exportTapped:(id)sender {     UIActionSheet *actionSheet = [[[UIActionSheet alloc]                                   initWithTitle:@""                                    delegate:self                                    cancelButtonTitle:@"Cancel"                                    destructiveButtonTitle:nil                                    otherButtonTitles:@"Export via File Sharing", @"Export via Email", nil] autorelease];    [actionSheet showInView:self.view]; }// Add new methods- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {     if (buttonIndex == actionSheet.firstOtherButtonIndex + 0) {         [DSBezelActivityView newActivityViewForView:self.navigationController.navigationBar.superview withLabel:@"Exporting Bug..." width:160];           [_queue addOperationWithBlock: ^{            BOOL exported = [_bugDoc exportToDiskWithForce:FALSE];            [[NSOperationQueue mainQueue] addOperationWithBlock:^{                [DSBezelActivityView removeViewAnimated:YES];                if (!exported) {                    UIAlertView *alertView = [[[UIAlertView alloc]                                                initWithTitle:@"File Already Exists!"                                                message:@"An exported bug with this name already exists.  Overwrite?"                                                delegate:self                                                cancelButtonTitle:@"Cancel"                                                otherButtonTitles:@"Overwrite", nil] autorelease];                    [alertView show];                }            }];        }];      } else if (buttonIndex == actionSheet.firstOtherButtonIndex + 1) {         [DSBezelActivityView newActivityViewForView:self.navigationController.navigationBar.superview withLabel:@"Exporting Bug..." width:160];           [_queue addOperationWithBlock: ^{            NSData *bugData = [_bugDoc exportToNSData];            [[NSOperationQueue mainQueue] addOperationWithBlock:^{                [DSBezelActivityView removeViewAnimated:YES];                if (bugData != nil) {                    MFMailComposeViewController *picker = [[[MFMailComposeViewController alloc] init] autorelease];                    [picker setSubject:@"My Scary Bug"];                    [picker addAttachmentData:bugData mimeType:@"application/scarybugs" fileName:[_bugDoc getExportFileName]];                    [picker setToRecipients:[NSArray array]];                    [picker setMessageBody:@"Check out this scary bug!  You‘ll need a copy of ScaryBugs to view this file, then tap and hold to open." isHTML:NO];                    [picker setMailComposeDelegate:self];                    [self presentModalViewController:picker animated:YES];                                    }             }];        }];      } }- (void)mailComposeController:(MFMailComposeViewController *)controller  didFinishWithResult:(MFMailComposeResult)resulterror:(NSError *)error {    [self dismissModalViewControllerAnimated:YES];}

Here, we changed the output button. In the pop-up window, we asked the user whether to use the same file sharing or email for output.
If you choose to share files via email, we will use mfmailcomposeviewcontroller to generate an email message and add attachments containing bug data. Is it easy?
The last thing before we start the test: Right-click frameworks and choose "addexisting framework ...", Select messageui. framework from the drop-down list ".
Next, compile and run your application. You should have been able to automatically output a "scary bug" from the application via email!

Fun!

If you have already done so much, why not be more fun?
Generate a scary bug through the application and send it to me via email. the email address is in, and I will add it to this tutorial! Let's take a look at what horrible creature we have created! :]
Update:This is a rare bug from Alex Hedley! :]

Where to go?

Here is the code of this tutorial series so far.
My plan is that there are so many scary bugs applications, but who knows? Maybe I will add more.
At the same time, if you have any questions, comments, or want to share what you think is the most terrible bug, please let me know! :]

Another article is also good:

Http://blog.spritebandits.com/2011/12/14/importing-csv-data-file-into-an-ios-app-via-email-attachment/
Http://blog.spritebandits.com/2011/12/21/importing-csv-data-file-into-an-ios-app-via-email-attachment-part-2/

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.