Data Attached in E-mail? - iphone

My NSMutableArray data are in NSData formate.I am trying to attached NSMutableArray data to E-mail body.Here is my NSMutableArray code:
NSUserDefaults *defaults1 = [NSUserDefaults standardUserDefaults];
NSString *msg1 = [defaults1 objectForKey:#"key5"];
NSData *colorData = [defaults1 objectForKey:#"key6"];
UIColor *color = [NSKeyedUnarchiver unarchiveObjectWithData:colorData];
NSData *colorData1 = [defaults1 objectForKey:#"key7"];
UIColor *color1 = [NSKeyedUnarchiver unarchiveObjectWithData:colorData1];
NSData *colorData2 = [defaults1 objectForKey:#"key8"];
UIFont *color2 = [NSKeyedUnarchiver unarchiveObjectWithData:colorData2];
CGFloat x =(arc4random()%100)+100;
CGFloat y =(arc4random()%100)+250;
lbl = [[UILabel alloc] initWithFrame:CGRectMake(x, y, 100, 70)];
lbl.userInteractionEnabled=YES;
lbl.text=msg1;
lbl.backgroundColor=color;
lbl.textColor=color1;
lbl.font =color2;
lbl.lineBreakMode = UILineBreakModeWordWrap;
lbl.numberOfLines = 50;
[self.view addSubview:lbl];
[viewArray addObject:lbl ];
viewArray is my NSMutableArray .All the data store in viewArray are in NSData formate.I try this code to attached viewArray data in E-mail.
- (IBAction)sendEmail {
if ([MFMailComposeViewController canSendMail])
{
NSArray *recipients = [NSArray arrayWithObject:#"example#yahoo.com"];
MFMailComposeViewController *controller = [[MFMailComposeViewController
alloc] init];
controller.mailComposeDelegate = self;
[controller setSubject:#"Iphone Game"];
NSLog(#"viewArray: %#", viewArray);
NSString *string = [viewArray componentsJoinedByString:#"\n"];
NSString *emailBody = string;
NSLog(#"test=%#",emailBody);
[controller setMessageBody:emailBody isHTML:YES];
[controller setToRecipients:recipients];
[self presentModalViewController:controller animated:YES];
[controller release];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Alert"
message:#"Your device is not set up for email." delegate:self
cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[alert release];
}
}
Here i see objects store in viewArray.in console its look like this..[2012-05-07 18:48:00.065 Note List[279:207] test=UILabel: 0x8250850; frame = (140 341; 56 19); text = 'Xxxxxxx'; clipsToBounds = YES; layer = > but in E-mail i see only this..>> please suggest any one how can i attached my viewArray data in E-mail.
]

in email attachement, you can only send NSData or string to email, now if you want to send it by string, then get all values you want to send email like, lable.text, lable.color, lable.alpha etc, with proper keys and place it in the body and parse there, else find some way to convert your object into NSData and attach it using mfmailcomposer attach data method
read this to convert NSArray into NSData
How to convert NSArray to NSData?
and this to convert back the NSData to NSArray
How can i convert a NSData to NSArray?
and then write this data to file as,
-(void)writeDataToFile:(NSString*)filename
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
if(filename==nil)
{
DLog(#"FILE NAME IS NIL");
return;
}
// the path to write file
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat: #"%#",filename]];
/*NSData *writeData;
writeData=[NSKeyedArchiver archivedDataWithRootObject:pArray]; */
NSFileManager *fm=[NSFileManager defaultManager];
if(!filePath)
{
//DLog(#"File %# doesn't exist, so we create it", filePath);
[fm createFileAtPath:filePath contents:self.mRespData attributes:nil];
}
else
{
//DLog(#"file exists");
[self.mRespData writeToFile:filePath atomically:YES];
}
NSMutableData *resData = [[NSMutableData alloc] init];
self.mRespData=resData;
[resData release];
}
and finally attach it to the email using
- (void)addAttachmentData:(NSData *)attachment mimeType:(NSString *)mimeType fileName:(NSString *)filename

Related

Attach image to message composer in ios 6

How to attach an image to native message composer in ios6? I want to implement the same sharing via message function we can see in default photos app.
Thanks
For Mail:
MFMailComposeViewController *mailController = [[MFMailComposeViewController alloc] init];
NSData *exportData = UIImageJPEGRepresentation(pic ,1.0);
[mailController addAttachmentData:exportData mimeType:#"image/jpeg" fileName:#"Photo.jpeg"];
[self presentModalViewController:mailController animated:YES];
The only way is through email currently. Unless you want to create a own MMS gateway to allow your app to support MMS..
For Message:
After reading up, instead of using MFMessageComposeViewController,you could UIApplication sharedApplication.
Example:
UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
pasteboard.persistent = YES;
NSData *data = UIImageJPEGRepresentation(pic ,1.0);
pasteboard.image = [UIImage imageWithData:data];
NSString *phoneToCall = #"sms: 123-456-7890";
NSString *phoneToCallEncoded = [phoneToCall stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSURL *url = [[NSURL alloc] initWithString:phoneToCallEncoded];
[[UIApplication sharedApplication] openURL:url];
Longpress and click on Paste and message will be pasted...
Hope this helps... pic refers to the UIImage you are passing...
{
NSMutableDictionary * attachment = [[NSMutableDictionary alloc]init];
[attachment setObject: UIImageJPEGRepresentation(imageView.image,0.5) forKey:#"attachmentData"];
[attachment setObject: #"productImage.jpeg" forKey:#"attachmentFileName"];
[attachment setObject: #"jpeg" forKey:#"attachmentFileMimeType"];
NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
[params setObject: #"subject" forKey:#"subject"];
[params setObject: #"matterText" forKey:#"matterText"];
[params setObject: [[NSMutableArray alloc]initWithObjects:attachment, nil] forKey:#"attachments"];
}
#pragma mark - Sharing Via Email Related Methods
-(void)emailInfo:(NSMutableDictionary*)info
{
if (![MFMailComposeViewController canSendMail])
{
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Email Configuration"
message:#"We cannot send an email right now because your device's email account is not configured. Please configure an email account from your device's Settings, and try again."
delegate:nil
cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alert show];
return;
}
MFMailComposeViewController *emailer = [[MFMailComposeViewController alloc] init];
emailer.mailComposeDelegate = self;
NSString * subject = [info objectForKey:#"subject"];
NSString * matterText = [info objectForKey:#"matterText"];
if(subject)
[emailer setSubject:subject];
if(matterText)
[emailer setMessageBody:matterText isHTML:NO];
NSMutableArray * attachments = [info objectForKey:#"attachments"];
if (attachments)
{
for (int i = 0 ; i < attachments.count ; i++)
{
NSMutableDictionary * attachment = [attachments objectAtIndex:i];
NSData * attachmentData = [attachment objectForKey:#"attachmentData"];
NSString * attachmentFileName = [attachment objectForKey:#"attachmentFileName"];
NSString * attachmentFileMimeType = [attachment objectForKey:#"attachmentFileMimeType"];
[emailer addAttachmentData:attachmentData mimeType:attachmentFileMimeType fileName:attachmentFileName];
}
}
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
emailer.modalPresentationStyle = UIModalPresentationPageSheet;
}
[self.navigationController.topViewController presentViewController:emailer animated:YES completion:nil];
}
I think you cant attach an image in the message composer. It is only possible in mail composer.

how to attach any document in email in iphone app

I am sending email from iphone app it is working fine but i want that with email i should attached a pdf file which is documents folder of the app.for testing first i attached a png from resources folder of app but it does not get attached and not sent in email i am using following code.
- (IBAction)onEmailResult
{
if ([[MFMailComposeViewController class] canSendMail]) {
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
[picker setSubject:#"Pig Game"];
[picker setToRecipients:toRecipients];
int a=10;
int b=100;
NSString *path = [[NSBundle mainBundle] pathForResource:#"project existing photo" ofType:#"png"];
NSData *myData = [NSData dataWithContentsOfFile:path];
[picker addAttachmentData:myData mimeType:#"png" fileName:#"icon.png"];
NSString * emailBody = [NSString stringWithFormat:#"My Score %d",a];
[picker setMessageBody:emailBody isHTML:NO];
[self presentModalViewController:picker animated:YES];
[picker release];
}
else {
int a=10;
int b=20;
NSString *recipients = #"mailto:imran_husain_2000#yahoo.com?&subject=Pig Game";
NSString *body = [NSString stringWithFormat:#"&body=My Score: %d/%d, My Time: %#", a,b, time];
NSString *email = [NSString stringWithFormat:#"%#%#", recipients, body];
email = [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:email]];
}
}
Try following code snippet.
- (NSString *)pathForFile : (NSString *) fileName{
return [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent: fileName];
}
- (void)sendMailWithAttachedFile:(NSString *) fileName extention:(NSString *) extension{
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
// NSURL* outputURL = [[NSURL alloc] initFileURLWithPath:[self pathForResourse:fileName ofType:extension]];
NSURL* outputURL = [[NSURL alloc] initFileURLWithPath:[self pathForFile:[NSString stringWithFormat:#"%#.%#", fileName, extension]]];
NSData *data=[[NSData alloc]initWithContentsOfURL:outputURL];
[picker addAttachmentData:data mimeType:#"application/pdf" fileName:#"TestOne.pdf"];
[self presentViewController:picker animated:YES completion:nil];
}
Now Call Send Mail method As:
[self sendMailWithAttachedFile:#"TestOne" :#"pdf"];
-(void)displayMailComposerSheet
{
NSData *soundFile = [[NSData alloc] initWithContentsOfURL:YourDocumentFile];
[mail addAttachmentData:soundFile mimeType:#".txt" fileName:#"YourDocumentFile.txt"];
}
This code implement in displayMailComposerSheet i hope this code is useful for You
MFMailComposeViewController *picker1 = [[MFMailComposeViewController alloc] init];
NSArray *recipentsArray = [[NSArray alloc]initWithObjects:[shopDictValues objectForKey:#"vEmail"], nil];
picker1.mailComposeDelegate = self;
picker1.modalPresentationStyle = UIModalPresentationFormSheet;
[picker1 setSubject:#"Subject"];
[picker1 setToRecipients:recipentsArray];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSMutableArray *arydefault = [[NSMutableArray alloc]initWithArray:[[NSUserDefaults standardUserDefaults] valueForKey:#"jacketCount"]];
for (int i=0;i<arydefault.count;i++)
{
NSString *pdfFilePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#%#.pdf",[[arydefault objectAtIndex:i]valueForKey:#"productlinename"],[arydefault objectAtIndex:i]]];
[picker1 addAttachmentData:[NSData dataWithContentsOfFile:pdfFilePath] mimeType:#"application/pdf" fileName:[NSString stringWithFormat:#"Order - %#",[[[NSString stringWithFormat:#"%#%i",[[arr objectAtIndex:i]valueForKey:#"productlinename"],i] componentsSeparatedByCharactersInSet: [[NSCharacterSet letterCharacterSet] invertedSet]] componentsJoinedByString:#""]]];
}
NSString *emailBody = #"Email Body goes here.";
[picker1 setMessageBody:emailBody isHTML:YES];
[self presentModalViewController:picker1 animated:YES];

How to send a label's text as an email attachment?

I want to attach a label text to an email,
How can I send a text inside a UILabel as an attachment to email ?
This is the code I'm using :
-(IBAction)send:(id)sender {
if ([MFMailComposeViewController canSendMail])
{
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 100, 300, 100)];
label.numberOfLines = 0;
label.textAlignment = UITextAlignmentCenter;
label.text = #"text";
[self.view addSubview:label];
[label release];
MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];
mailer.mailComposeDelegate = self;
[mailer setSubject:#"Subject"];
NSString *fileName = #"my file.txt";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:fileName];
NSData *myData = [NSData dataWithContentsOfFile:path];
[mailer addAttachmentData:myData mimeType:#"text/plain" fileName:fileName];
// Fill out the email body text
NSString *emailBody = #"Email Body";
[mailer setMessageBody:emailBody isHTML:NO];
[self presentModalViewController:mailer animated:YES];
[mailer release];
}
else
{
UIAlertView *alertm = [[UIAlertView alloc] initWithTitle:#"Failure"
message:#"Please make sure that your email application is open"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[alertm show];
[alertm release];
}
}
How can I link that label to attach it to email ?
Any help will be appreciated.
you're almost there.
-- you read text from a file and attach it
===
read the data not from the file but from the label itself
NSData *data = [self.label.text dataUsingEncoding:NSUTF8Encoding];
You can add the Label text to the Body.
NSString *emailBody = [NSString stringWithFormat:#"Your Voice File Attached. %#", label.text];
something like this

UIAlertView kind of contradicts the UIActivityIndicator

I'm downloading the images from the online image for cache when offline. When I open application, The image was downloaded all completely before UIAlertView pop. It's finish incorrectly. I want to make the UIAlertView pop before images download. Here there are my code below.
- (void) operatePopupUpdating {
myAlert = [[UIAlertView alloc] initWithTitle:#"Updating database.." message:nil delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
[myAlert show];
UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
indicator.center = CGPointMake(myAlert.bounds.size.width / 2, myAlert.bounds.size.height - 50);
[indicator startAnimating];
[myAlert addSubview:indicator];
[self operateUpdate];
[self updateImage];
[self operationCompleted];
}
In updateImage, operateUpdate and operationCompleted Method
- (void)updateImage {
NSString *snake_ico_file = #"snake_img_icn_";
NSString *filePath = [self dataFile:[snake_ico_file stringByAppendingString:#"0.jpg"]];
int max_count = [[self readData] count];
if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
for (int i = 0; i < max_count; i++) {
NSString *path = #"http://exitosus.no.de/drngoo/image/";
path = [path stringByAppendingFormat:#"%d",i];
NSString *ico_path = [path stringByAppendingFormat:#"/ico"];
//icon
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filename = [snake_ico_file stringByAppendingFormat:#"%d.jpg"];
NSString *localFilePath = [documentsDirectory stringByAppendingPathComponent:filename];
NSData *thedata = [NSData dataWithContentsOfURL:[NSURL URLWithString:ico_path]];;
[thedata writeToFile:localFilePath atomically:YES];
}
}
-(void) operationCompleted
{
[myAlert dismissWithClickedButtonIndex:0 animated:YES];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Message form System" message:#"Database was updated successful" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
}
- (void)operateUpdate {
NSString *filePath = [self dataFileSettingPath];
int updatedVer = 0;
int version = [self checkDatabase];
if (version == -1) {
updatedVer = [self createDataBase:0];
} else {
updatedVer = [self updateDataBase:version];
}
[self.settingInfo setObject:[NSString stringWithFormat:#"%d",updatedVer] forKey:#"DBVersion"];
[self.settingInfo writeToFile:filePath atomically:YES];
}
How I fix them and work correctly?
The alertView will show only after your image downloading complete. One Solution to solve this is,
Create another class ImageDownLoad.h
in .h
#property(nonatomic,assign)id delegate;
#property(nonatomic,retain) NSString *path;
in .m
#synthesize delegate;
#synthesize path;
Create a method namely,
-(void)startDownloadImageWithUrl:(NSURL*)imageUrl withLocalFilePath:(NSSTring*)filePath{
path = filePath;
receiveData = [NSMutableData data];
NSURLRequest *request = [[NSURLRequest alloc]initWithURL:imageUrl];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[receiveData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
[(id)delegate performSelector:#selector(SaveData:inFilePath:) withObject:receiveData withObject:path];
}
This will create connection and start download your image in a separate class. Then in your mai ViewController add bit of code like below.
- (void)updateImage {
NSString *snake_ico_file = #"snake_img_icn_";
NSString *filePath = [self dataFile:[snake_ico_file stringByAppendingString:#"0.jpg"]];
int max_count = [[self readData] count];
if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
for (int i = 0; i < max_count; i++) {
NSString *path = #"http://exitosus.no.de/drngoo/image/";
path = [path stringByAppendingFormat:#"%d",i];
NSString *ico_path = [path stringByAppendingFormat:#"/ico"];
//icon
NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filename = [snake_ico_file stringByAppendingFormat:#"%d.jpg"];
NSString *localFilePath = [documentsDirectory stringByAppendingPathComponent:filename];
ImageDownLoad *imageDown = [[ImageDownLoad alloc]init];
imageDown.delegate = self;
[imageDown startDownloadImageWithUrl:[NSURL URLWithString:ico_path] withLocalFilePath:localFilePath];
}
}
This method will be called each time when image download completes.
-(void)SaveData:(NSData*)data inFilePath:(NSString*)filePath{
[data writeToFile:filePath atomically:YES];
}
Your UI wont delay by doing so :)

Find Photo in Directory! (Programmatically)

Holy Dudes from stackoverflow,
MY PROBLEM: I need to send an email with 3 attachments. The first that is the .txt, is going well, no problems with him, but the problem is with the pictures. I capture a printscreen with this:
-(IBAction)screenShot{
maintimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:#selector(update) userInfo:nil repeats:YES];
}
-(void)update{
time = time + 1;
if(time == 2){
[self hideThem]; //hides the buttons
UIGraphicsBeginImageContext(self.bounds.size);
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *screenImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageWriteToSavedPhotosAlbum(screenImage, nil, nil, nil);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"GRAPH SAVED" message:#"YOUR GRAPH HAS BEEN SAVEN IN THE PHOTO ALBUM" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
[maintimer invalidate];
time = 0;
}
[self bringThem]; //brings the buttons back
}
But now i need to get this image i created! I tried using the same code i use for the text:
-(IBAction)sendMail
{
(..)
//HERE IS WHERE THE NAME IS GIVEN
NSString *filename = [NSString stringWithFormat:#"%f.txt", [[NSDate date] timeIntervalSince1970]];
//THIS IS GOING TO STORE MY MESSAGE STUFF
NSString *content = [[NSMutableString alloc]init];
(...) //LOTS OF UNNECESSARY CODE
//HERE IS WHERE IT BILDS THE FILE
[self writeToTextFile:filename content:content];
//HERE IS THE CODE WHERE IT ATTACHES THE FILE
[self sendMailWithFile:filename];
//[content release];
}
-(void)sendMailWithFile : (NSString *)file
{
//THIS IS THE CODE THAT GETS THE TEXT
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fileName = [NSString stringWithFormat:#"%#/%#", documentsDirectory, file];
NSData *data = [[NSData alloc] initWithContentsOfFile:fileName];
//THIS WAS MY TRY TO GET THE PHOTO ON THE SAME STYLE OF THE TEXT
NSArray *photoPath = NSSearchPathForDirectoriesInDomains(NSPicturesDirectory, NSUserDomainMask, YES);
NSString *photoDirectoryForFirstPhoto = [photoPath objectAtIndex:0];
NSString *photoName_First = [NSString stringWithFormat:#"%#/%#", photoDirectoryForFirstPhoto, /*I DO NOT HAVE THE PHOTO NAME*/#"FirstPhoto"];
NSData *photoData_First = [[NSData alloc] initWithContentsOfFile:photoName_First];
MFMailComposeViewController *mailComposer = [[MFMailComposeViewController alloc] init];
if ([MFMailComposeViewController canSendMail])
{
mailComposer = [[MFMailComposeViewController alloc] init];
mailComposer.mailComposeDelegate = self;
[mailComposer setSubject:#"RK4 data"];
[mailComposer addAttachmentData:data mimeType:#"text/plain" fileName:#"[RK4][EQUATION][TEXT]"];
[mailComposer addAttachmentData:photoData_First mimeType:#"image/png" fileName:#"[RK4][EQUATION][IMAGE]"];
[mailComposer setMessageBody:#"iCalculus Runge-Kutta data." isHTML:NO];
[self presentModalViewController:mailComposer animated:YES];
}
else (...)
[mailComposer release];
[data release];
}
So that's my problem. I need to find a way to get the printscreen i took and attach it.
Because i need to come up with all the attaches in the email as soon as he clicks the "SEND MAIL" button.
Thanks.
Rather than saving to your photo library, you should save to documents directory, or tmp directory, to get documents directory you can use the following.
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* dd = [paths objectAtIndex:0];
NSString *path = [dd stringByAppendingPathComponent:#"file.png"];
[UIImagePNGRepresentation(screenImage) writeToFile:path atomically:NO];
Take a look here for how to embed the image directly inside the email using base-64, that should be much cleaner than dumping temporary images to the users saved photos album.
Edit:
Category for handling base 64 with NSData, use the download towards the bottom.