Retrieve saved image from app and email - iphone

I am succesfully saving an image to my app after the user takes a picture. What I want to do later is, when the user comes back to the app I want them to be able to email the photo as an attachment. I am not having any luck getting the data from the app converted to an image so I can add as an attachment. Can someone point me in the right direction please. Here is where I save the image after they have taken a picture.
- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info
{
//here is the image returned
app.aImage2 = [info objectForKey:UIImagePickerControllerOriginalImage];
NSData *imageData = UIImagePNGRepresentation( app.aImage2 );
NSString * savedImageName = [NSString stringWithFormat:#"r%#aImage2.png",app.reportNumber];
NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * documentsDirectory = [paths objectAtIndex:0];
NSString * dataFilePath;
dataFilePath = [documentsDirectory stringByAppendingPathComponent:savedImageName];
[imageData writeToFile:dataFilePath atomically:YES];
[self dismissModalViewControllerAnimated:YES];
}
And here is where I need to attach it.
//this is inside my method that creates an email composer view
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self; // <- very important step if you want feedbacks on what the user did with your email sheet
//how would i attach the saved image from above?

This includes code that Mike mentions here:
How to add a UIImage in MailComposer Sheet of MFMailComposeViewController
Also, other portions are lifted from Sagar Kothari's answer here:
Sending out HTML email with IMG tag from an iPhone App using MFMailComposeViewController class
- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info
{
// Dismiss image picker modal.
[picker dismissModalViewControllerAnimated:YES];
if ([MFMailComposeViewController canSendMail]) {
// Create a string with HTML formatting for the email body.
NSMutableString *emailBody = [[NSMutableString alloc] initWithString:#"<html><body>"];
// Add some text to it.
[emailBody appendString:#"<p>Body text goes here.</p>"];
// You could repeat here with more text or images, otherwise
// close the HTML formatting.
[emailBody appendString:#"</body></html>"];
NSLog(#"%#", emailBody);
// Create the mail composer window.
MFMailComposeViewController *emailDialog = [[MFMailComposeViewController alloc] init];
emailDialog.mailComposeDelegate = self;
// Image to insert.
UIImage *emailImage = [info objectForKey:UIImagePickerControllerOriginalImage];
if (emailImage != nil) {
NSData *data = UIImagePNGRepresentation(emailImage);
[emailDialog addAttachmentData:data mimeType:#"image/png" fileName:#"filename_goes_here.png"];
}
[emailDialog setSubject:#"Subject goes here."];
[emailDialog setMessageBody:emailBody isHTML:YES];
[self presentModalViewController:emailDialog animated:YES];
[emailDialog release];
[emailBody release];
}
}

Related

Attaching multiple image to an email

I am using ELCimagepicker to attach multiple image to an email but I'm not sure how to make every NSData unique so i can attach them to my email.
>
- (void)launchController {
ELCAlbumPickerController *albumController = [[ELCAlbumPickerController alloc] initWithNibName:#"ELCAlbumPickerController" bundle:[NSBundle mainBundle]];
ELCImagePickerController *elcPicker = [[ELCImagePickerController alloc] initWithRootViewController:albumController];
[albumController setParent:elcPicker];
[elcPicker setDelegate:self];
[self presentModalViewController:elcPicker animated:YES];
}
- (void)elcImagePickerController:(ELCImagePickerController *)picker didFinishPickingMediaWithInfo:(NSArray *)info {
[self dismissModalViewControllerAnimated:YES];
int i = 0;
for(NSDictionary *dict in info) {
i++;
UIImageView *imageview = [[UIImageView alloc] initWithImage:[dict objectForKey:UIImagePickerControllerOriginalImage]];
NSData *name = UIImageJPEGRepresentation(imageview, 1.0);
}
}
Get the app from this link
https://github.com/elc/ELCImagePickerController
and following changes from the code
using for loop
-(IBAction)launchController
{
ELCAlbumPickerController *albumController = [[ELCAlbumPickerController alloc] initWithNibName:#"ELCAlbumPickerController" bundle:[NSBundle mainBundle]];
ELCImagePickerController *elcPicker = [[ELCImagePickerController alloc] initWithRootViewController:albumController];
[albumController setParent:elcPicker];
[elcPicker setDelegate:self];
ELCImagePickerDemoAppDelegate *app = (ELCImagePickerDemoAppDelegate *)[[UIApplication sharedApplication] delegate];
[app.viewController presentModalViewController:elcPicker animated:YES];
[elcPicker release];
[albumController release];
[self buttonPressed];
}
- (void)buttonPressed
{
// Create image picker controller
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
// Set source to the camera
imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
// Delegate is self
imagePicker.delegate = self;
// Allow editing of image ?
imagePicker.allowsImageEditing = NO;
// Show image picker
[self presentModalViewController:imagePicker animated:YES];
}
- (void)emailImage:(UIImage *)image
{
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
// Set the subject of email
[picker setSubject:#"Picture from my iPhone!"];
// Add email addresses
// Notice three sections: "to" "cc" and "bcc"
[picker setToRecipients:[NSArray arrayWithObjects:#"emailaddress1#domainName.com", #"emailaddress2#domainName.com", nil]];
[picker setCcRecipients:[NSArray arrayWithObject:#"emailaddress3#domainName.com"]];
[picker setBccRecipients:[NSArray arrayWithObject:#"emailaddress4#domainName.com"]];
// Fill out the email body text
NSString *emailBody = #"I just took this picture, check it out.";
for (int i=0; i<[imagedelegate.imgarray count]; i++)
{
UIImageView *image=[[UIImageView alloc] init];
image=[imagedelegate.imgarray objectAtIndex:i];
// This is not an HTML formatted email
[picker setMessageBody:emailBody isHTML:NO];
// Create NSData object as PNG image data from camera image
NSData *data = UIImagePNGRepresentation(image);
// Attach image data to the email
// 'CameraImage.png' is the file name that will be attached to the email
[picker addAttachmentData:data mimeType:#"image/png" fileName:#"CameraImage"];
// Show email view
[self presentModalViewController:picker animated:YES];
// Release picker
[picker release];
}
}
- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
// Access the uncropped image from info dictionary
UIImage *image = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
// Dismiss the camera
[self dismissModalViewControllerAnimated:YES];
// Pass the image from camera to method that will email the same
// A delay is needed so camera view can be dismissed
[self performSelector:#selector(emailImage:) withObject:image afterDelay:1.0];
// Release picker
[picker release];
}
Download and drag the Objective-Zip, MiniZip and ZLib drag in to your project from this link http://code.google.com/p/objective-zip/downloads/list (Objective-zip).. import the files: ZipFile.h, ZipException.h, FileInZipInfo.h, ZipWriteStream.h, ZipReadStream.h, zlib.h
Use the following code:
NSString *stringPath1 = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]];
NSString *FileName=[stringPath1 stringByAppendingPathComponent:#"Your file name"];
NSString *stringPath=[stringPath1 stringByAppendingPathComponent:[#"Your file name" stringByAppendingFormat:#".zip"]];
NSArray *files = [[NSFileManager defaultManager]contentsOfDirectoryAtPath:FileName error:&error];
ZipFile *zipFile = [[ZipFile alloc]initWithFileName:stringPath mode:ZipFileModeCreate];
for(int i = 0;i<files.count;i++){
id myArrayElement = [files objectAtIndex:i];
NSLog(#"add %#", myArrayElement);
NSString *path = [FileName stringByAppendingPathComponent:myArrayElement];
NSDictionary *attributes = [[NSFileManager defaultManager]attributesOfItemAtPath:path error:&error];
NSDate *Date = [attributes objectForKey:NSFileCreationDate];
ZipWriteStream *streem = [zipFile writeFileInZipWithName:myArrayElement fileDate:Date compressionLevel:ZipCompressionLevelBest];
NSData *data = [NSData dataWithContentsOfFile:path];
[streem writeData:data];
[streem finishedWriting];
}
[zipFile close];

Emailing photo taken with ImagePickerController?

In my app I want to:
a.) Present camera to user to take picture
b.) Create email and attach picture taken
I figured out how to take the picture. But, I don't know how to attach it to the email. In the examples I've seen the filename is known. This is one example.
picker.mailComposeDelegate = self;
[picker setSubject:#"I have a pencil for you"];
UIImage *roboPic = [UIImage imageNamed:#"RobotWithPencil.jpg"];
NSData *imageData = UIImageJPEGRepresentation(roboPic, 1);
[picker addAttachmentData:imageData mimeType:#"image/jpg" fileName:#"RobotWithPencil.jpg"];
NSString *emailBody = #"This is a cool image of a robot I found. Check it out!";
[picker setMessageBody:emailBody isHTML:YES];
[self presentModalViewController:picker animated:YES];
I am getting the image from the callback method and it does get stored in the camera roll.
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
// Access the uncropped image from info dictionary
UIImage *image = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
[picker dismissModalViewControllerAnimated:TRUE];
[picker release];
}
But from there, I'm not sure how to attach the image to the email? Mainly because I don't know what the filename is when a photo is added to the camera roll when the UIImagePickerController camera source is used to obtain it?
So, I guess I need to either:
a.) Find a way to get the name of the image file once it is saved OR
b.) Another way to attach UIImage data as an email attachment.
Any help appreciated.
maybe I don't understand what you are trying to do UI wise, but why would this not work from your code provide:
EDIT: (changed code to use a delegate)
- (void)imagePickerController:(UIImagePickerController *)imagepicker didFinishPickingMediaWithInfo:(NSDictionary *)info {
// Access the uncropped image from info dictionary
UIImage *image = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
if([delegate respondsToSelector:#selector(didSelectImage:)])
[delegate didSelectImage:image];
}
this goes in your header file (usually above your class declaration):
#protocol PostHelperDelegate <NSObject>
#optional
- (void)DimissModal;
//image data for image selected
- (void)DidSelectImage:(UIImage*)image;
#end
also you need to create this property in your class
#property(nonatomic,assign)id<PostHelperDelegate>* delegate; //don't forgot to synthizie
then in the class implementing the delegate you will assign the delegate your class:
Poster = [[delegateclass alloc] init];
Poster.delegate = self;
then just add the delegate function:
- (void)DidSelectImage:(UIImage*)image
{
//handle image here
}
I simplify this quite a bit, let me know if you have any trouble getting it working
http://www.roostersoftstudios.com/2011/04/12/simple-delegate-tutorial-for-ios-development/
BEFORE UPDATE:
personally I would use a delegate to notify that the image has been picked and than launch the mail picker, but that is another thing. As far as the UIImage, I don't know a way or have never found a way to name/or get a name from the UIImagePicker as I do not believe they are named anything meaningful. Any questions on the delegate or further explanation let me know.
use bellow code
-(void)yourmethodname_clicked{
UIImagePickerController * picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentModalViewController:picker animated:YES];
}
else{
UIAlertView *altnot=[[UIAlertView alloc]initWithTitle:#"Camera Not Available" message:#"Camera Not Available" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[altnot show];
[altnot release];
}
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
[picker dismissModalViewControllerAnimated:YES];
MFMailComposeViewController *mailpicker = [[MFMailComposeViewController alloc] init];
[mailpicker.navigationBar setTintColor:[UIColor blackColor]];
mailpicker.mailComposeDelegate = self;
[mailpicker setSubject:#"set your subject"];
NSArray *toRecipients = [NSArray arrayWithObjects: nil];
[mailpicker setToRecipients:toRecipients];
UIImage *picture = [info objectForKey:#"UIImagePickerControllerOriginalImage"]];;
NSData *imageData = UIImagePNGRepresentation(picture);
[mailpicker addAttachmentData:imageData mimeType:#"image/png" fileName:#"set your file name"];
NSString *emailBody = #"set your body string";
[mailpicker setMessageBody:emailBody isHTML:YES];
[mailpicker setSubject:#"set your subject"];
mailpicker.title = #"Email";
[self presentModalViewController:mailpicker animated:YES];
[mailpicker release];
}
may this help you

UIImagePickerViewController memory warning in iphone while getting image from photolibrary

when i run this program on iphone after adding thre to four image memory warning come and app crash. so please help me Thanks i just get image reference and write on file and then getting image from file path. Thanks
- (IBAction)addPicsButtonClick:(id)sender
{
UIImagePickerController * picker = [[[UIImagePickerController alloc] init] autorelease];
picker.delegate = self;
picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
[self presentModalViewController:picker animated:YES];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[picker dismissModalViewControllerAnimated:YES];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *pathToDocuments=[paths objectAtIndex:0];
AppDelegate *app = [[UIApplication sharedApplication] delegate];
NSData *imageData = UIImageJPEGRepresentation([info objectForKey:#"UIImagePickerControllerOriginalImage"], 0.3f);
[imageData writeToFile:[NSString stringWithFormat:#"%#/%d.jpg", pathToDocuments, [app.images count]] atomically:YES];
[self dismissModalViewControllerAnimated:YES];
}
I ran the same code in a new app in the simulator, and had no crash problem or memory warning, and it created the files. I did take out [app.images count] and used a local variable instead, as app.images is not set anywhere in this code. So if that variable is trash or over-released, that might be your problem.

iPhone Audio Record with Export/Email

I have searched all over Apples website and the internet as well as Stackoverflow. Does anyone have any sample code or a tutorial of how I can record audio from the built in mic, and then export that audio via email? Please, I really need it for my app. Thanks.
I used code from Apple's SpeakHere example app to record sound from the built-in mic to the wav file "recordedFile.wav", then added the following methods to the view controller to email the wav file as an attachment:
- (void)mailComposeController:(MFMailComposeViewController*)controller
didFinishWithResult:(MFMailComposeResult)result
error:(NSError*)error {
[self becomeFirstResponder];
[self dismissModalViewControllerAnimated:YES];
}
- (void)mailAttachedWavFile {
MFMailComposeViewController *picker =
[[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
[picker setSubject:#"My Wav File"]; // optional
NSString *fileName = #"recordedFile.wav"; // whatever
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:fileName];
NSData *data = [NSData dataWithContentsOfFile:path];
[picker addAttachmentData:data mimeType:#"audio/x-wav"
fileName:fileName];
NSString *emailBody = #"Wav format sound file attached."; // optional
[picker setMessageBody:emailBody isHTML:YES];
[self presentModalViewController:picker animated:YES];
[picker release];
}
You can make the mailAttachedWavFile method an IBOutlet from a button. Don't forget to declare the controller as a MFMailComposeViewControllerDelegate in the header file.

iphone email attachment

I used the MessageUI framework to send the mail with attachment from my application.
But i got the following error,
2009-09-07 19:52:23.483 emailTest[11711:5b17]
Error loading /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.0.sdk/System/Library/DataClassMigrators/AccountMigrator.migrator/AccountMigrator: dlopen(/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.0.sdk/System/Library/DataClassMigrators/AccountMigrator.migrator/AccountMigrator, 265): Library not loaded: /System/Library/PrivateFrameworks/MobileWirelessSync.framework/MobileWirelessSync
Referenced from: /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.0.sdk/System/Library/DataClassMigrators/AccountMigrator.migrator/AccountMigrator
Reason: image not found
2009-09-07 19:52:23.489 emailTest[11711:5b17] [+[AccountsManager _migrateAccountsIfNeeded]] Accounts migration failed
[Switching to process 11711 local thread 0xf03]
my code is,
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc]init];
picker.mailComposeDelegate = self;
[picker setSubject:#"This is iPhone email attachment test"];
UIImage *sampleImg = [UIImage imageNamed:#"iPhone.jpg"];
NSData *imageData = UIImageJPEGRepresentation(sampleImg, 1);
[picker addAttachmentData:imageData mimeType:#"image/png" fileName:#"iPhone.jpg"];
NSString *emailBody = #"I am sending the image attachment with iPhone email service";
[picker setMessageBody:emailBody isHTML:YES];
[self presentModalViewController:picker animated:YES];
[picker release];
please help me.
You do not have to type extension in your filename. like "iphone.jpg" is not working. just write "iphone" in filename because you already define mimeType. And also you have to define path for resource.
Below is the sample code to attach "rainy.png" file with mail.
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
[picker setSubject:#"Hello"];
// Set up recipients
NSArray *toRecipients = [NSArray arrayWithObject:#"first#example.com"];
NSArray *ccRecipients = [NSArray arrayWithObjects:#"second#example.com", #"third#example.com", nil];
NSArray *bccRecipients = [NSArray arrayWithObject:#"fourth#example.com"];
[picker setToRecipients:toRecipients];
[picker setCcRecipients:ccRecipients];
[picker setBccRecipients:bccRecipients];
// Attach an image to the email
NSString *path = [[NSBundle mainBundle] pathForResource:#"rainy" ofType:#"png"];
NSData *myData = [NSData dataWithContentsOfFile:path];
[picker addAttachmentData:myData mimeType:#"image/png" fileName:#"rainy"];
// Fill out the email body text
NSString *emailBody = #"It is raining";
[picker setMessageBody:emailBody isHTML:NO];
[self presentModalViewController:picker animated:YES];
[picker release];
This error seems to be related to the running mail int he simulator and not to your code. Even stock Apple's sample MailComposer reports identical error in the simulator:
2009-11-12 20:30:39.270 MailComposer[7426:4f1f] Error loading /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.0.sdk/System/Library/DataClassMigrators/AccountMigrator.migrator/AccountMigrator: dlopen(/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.0.sdk/System/Library/DataClassMigrators/AccountMigrator.migrator/AccountMigrator, 265): Library not loaded: /System/Library/PrivateFrameworks/MobileWirelessSync.framework/MobileWirelessSync
Referenced from: /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.0.sdk/System/Library/DataClassMigrators/AccountMigrator.migrator/AccountMigrator
Reason: image not found
2009-11-12 20:30:39.271 MailComposer[7426:4f1f] [+[AccountsManager _migrateAccountsIfNeeded]] Accounts migration failed
Add following method to dismiss the MFMailComposeViewController:
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult: (MFailComposeResult)result error:(NSError*)error
{
// NEVER REACHES THIS PLACE
[self dismissModalViewControllerAnimated:YES];
NSLog (#"mail finished");
}
use this for attach image in a mail, tested in ios 4,5,6
MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];
UIImage *myImage = [UIImage imageNamed:#"image.png"];
NSData *imageData = UIImagePNGRepresentation(myImage);
[mailer addAttachmentData:imageData mimeType:#"image/png" fileName:#"image"];