将图像附加到电子邮件中

时间:2012-08-17 01:17:58

标签: ios ipad

我想知道是否有办法允许用户从相机胶卷中选择图像,然后将其附加到电子邮件中?

以下是我现在的代码:

-(IBAction) openEmail {

MFMailComposeViewController *mailComposer = [[MFMailComposeViewController alloc] init];
[mailComposer setMailComposeDelegate:self];
if ([MFMailComposeViewController canSendMail]) {
    [mailComposer setToRecipients:[NSArray arrayWithObjects:@"TPsecondary_Example@email.com", nil]];
    [mailComposer setSubject:@"Learning Trail Submission"];
    [mailComposer setMessageBody:emailbody isHTML:NO];
    [mailComposer setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];

    NSString *path = [[NSBundle mainBundle] pathForResource:@"Answer" ofType:@"plist"];
    NSData *myData = [NSData dataWithContentsOfFile:path];
    [mailComposer addAttachmentData:myData mimeType:@"application/xml" fileName:@"Answer.plist"];

    [self presentModalViewController:mailComposer animated:YES];
}
}

1 个答案:

答案 0 :(得分:1)

肯定有!

在你的.h文件中添加这些代理并声明一个名为selectedImage的UIImage

<UIImagePickerControllerDelegate, UINavigationControllerDelegate>

然后在你的.m中你可以添加以下内容。

-(IBAction)openImagePicker:(id)sender链接到您要启动流程的按钮。

- (IBAction)openImagePicker:(id)sender
{

    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
    {
        UIImagePickerController *imagePicker =
        [[UIImagePickerController alloc] init];
        imagePicker.delegate = self;
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagePicker.allowsEditing = NO;
        [self presentViewController:imagePicker animated:YES completion:nil];
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    selectedImage = [info objectForKey:UIImagePickerControllerOriginalImage];
    [self dismissViewControllerAnimated:YES completion:^{
        [self openEmail];
    }];

}

-(IBAction) openEmail {

    MFMailComposeViewController *mailComposer = [[MFMailComposeViewController alloc] init];
    [mailComposer setMailComposeDelegate:self];
    if ([MFMailComposeViewController canSendMail]) {
        [mailComposer setToRecipients:[NSArray arrayWithObjects:@"TPsecondary_Example@email.com", nil]];
        [mailComposer setSubject:@"Learning Trail Submission"];
        [mailComposer setMessageBody:emailbody isHTML:NO];
        [mailComposer setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];

        NSString *path = [[NSBundle mainBundle] pathForResource:@"Answer" ofType:@"plist"];
        NSData *myData = [NSData dataWithContentsOfFile:path];
        [mailComposer addAttachmentData:myData mimeType:@"application/xml" fileName:@"Answer.plist"];
        NSData *imageData = UIImageJPEGRepresentation(selectedImage, 1.0);
        [mailComposer addAttachmentData:imageData  mimeType:@"image/jpg"   fileName:@"imageTitle"];
        [self presentModalViewController:mailComposer animated:YES];
    }
}

编辑:请注意,这是一个非常基本的示例,无法处理用户选择视频而非图像等事件...