Find Photo in Directory! (Programmatically) - iphone

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.

Related

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

Data Attached in E-mail?

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

Plist file path error?

I am trying to save an NSMutableArray containing text to a plist file using this code:
- (IBAction)saveDoc:(id)sender
{
NSString *typedText = typingArea.text;
NSMutableArray *totalFiles = [[NSMutableArray alloc] initWithObjects:typedText, nil];
NSLog(#"Created: %#", totalFiles);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"savedFiles.plist"];
NSLog(#"Found Path: %#", path);
//[totalFiles addObject:typedText];
[totalFiles writeToFile:path atomically:YES];
NSLog(#"File Written: %# to: %#", totalFiles, path);
[totalFiles release];
NSLog(#"Released: %#", totalFiles);
}
All of the NSLogs return appropriate values as expected. I use this code to crate a new NSMutableArray with the contents of the plist:
- (void)viewDidLoad {
file = [[NSBundle mainBundle] pathForResource:#"savedFiles" ofType:#"plist"];
NSLog(#"Got Path: %#", file);
array = [NSMutableArray arrayWithContentsOfFile:file];
NSLog(#"Loaded Array into new array: %#", array);
//UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:#"fdsfasdf" message:[dic objectForKey:#"item1"] delegate:self cancelButtonTitle:#"ldfghjfd" otherButtonTitles:nil] autorelease];
//[alert show];
[super viewDidLoad];
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
//self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
The NSLogs in this code come back with a slightly different path than the first one returned with. It also said the array is (null)
How should I load the contents from a plist file?
Thanks in advance,
Tate
Try initialising your array first:
array = [[NSMutableArray alloc] initWithContentsOfFile:file];

Attachment doesn't displayed in mail which is sent through iPhone

I have send an attachment through iPhone application.
But when I see the mail, I can see the upin that shows that something is attached.
But when I open the mail I couldn't found any attachment?
What is the problem behind this?
-(IBAction)btnPressedExport:(id)sender{
NSArray *x=[[NSArray alloc] initWithArray:[DatabaseAccess getAllTransactionsForUserID:[BudgetTrackerAppDelegate getUserID] profileID:[BudgetTrackerAppDelegate getProfileID]]];
int i=-1,j=[x count];
NSDictionary *tmp;
NSMutableString *stringToWrite=[[NSMutableString alloc] init];
for(;i<j;i++){
if(i==-1){
[stringToWrite appendString:#"TransactionID,TransactionDate,ProfileName,ProfileType,GroupName,GroupType,CategoryName,TransactionAmt\n"];
} else {
tmp=[x objectAtIndex:i];
[stringToWrite appendFormat:#"%#,%#,%#,%#,%#,%#,%#,%#\n",
[tmp valueForKey:#"TraID"],[tmp valueForKey:#"TraDate"],[tmp valueForKey:#"ProfileName"],[tmp valueForKey:#"ProfileType"],[tmp valueForKey:#"GroupName"],[tmp valueForKey:#"GroupType"],[tmp valueForKey:#"CatName"],[tmp valueForKey:#"TraAmt"]];
}
}
[stringToWrite writeToFile:[self pathOfCSVForExport] atomically:YES encoding:NSStringEncodingConversionAllowLossy error:nil];
// [stringToWrite writeToFile:[self pathOfCSVForExport] atomically:YES];
picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate=self;
// picker.delegate=self;
[picker setSubject:#"Hello from Sugar!"];
//Set up recipients
NSArray *toRecipients = [NSArray arrayWithObject:#"sugar.srk#pqr.com"];
// NSArray *ccRecipients = [NSArray arrayWithObjects:#"xyz.dalal#pqr.com", #"kandarp.dave#phptalent.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:#"myExport" ofType:#"csv"];
NSData *myData = [NSData dataWithContentsOfFile:path];
NSString *fileNameToSend=#"BudgetTracker.csv";//[NSString stringWithFormat:#"%#.csv",[x valueForKey:#"ProfileName"]];
[picker addAttachmentData:myData mimeType:#"text/plain" fileName:fileNameToSend];
// text/html/
// Fill out the email body text
NSString *emailBody = [NSString stringWithFormat:#"%#",#"Hello! This is export test."];
[picker setMessageBody:emailBody isHTML:NO];
[self presentModalViewController:picker animated:YES];
}
-(void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error{
// NSLog(#"here2");
switch (result)
{
case MFMailComposeResultCancelled: break;
case MFMailComposeResultSaved: break;
case MFMailComposeResultSent: break;
case MFMailComposeResultFailed: break;
default: break;
}
// self.navigationController.navigationBarHidden=NO;
// [self becomeFirstResponder];
[self dismissModalViewControllerAnimated:YES];
}
This looks wrong, unless it's just for testing:
// Attach an image to the email
NSString *path = [[NSBundle mainBundle] pathForResource:#"myExport" ofType:#"csv"];
NSData *myData = [NSData dataWithContentsOfFile:path];
the path you're using is to a file in your application bundle, which is read-only, so it can't be the CSV file you just made.
if you want to write a temporary file and email it, you need to write it to someplace like your Documents directory, i.e. a path like
NSArray *sysPaths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES );
NSString *docDirectory = [sysPaths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/myexport.csv", docDirectory];