Sending a email with pdf attachment from documents directory Objective c - ios

I am having issues getting my program to accept the path I gave it and returning it as NSData
// Get the resource path and read the file using NSData
NSString *searchFilename = #"SafetyAuditReport.pdf"; // name of the PDF you are searching for
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath:documentsDirectory];
NSString *documentsSubpath;
while (documentsSubpath = [direnum nextObject])
{
if (![documentsSubpath.lastPathComponent isEqual:searchFilename]) {
continue;
}
NSLog(#"found %#", documentsSubpath);
}
NSData *pdfData = [NSData dataWithContentsOfFile:documentsSubpath];
// Determine the MIME type
NSString *mimeType = #"application/pdf";
MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
mc.mailComposeDelegate = self;
[mc setSubject:emailTitle];
[mc setMessageBody:messageBody isHTML:NO];
[mc setToRecipients:toRecipents];
[mc addAttachmentData:pdfData mimeType:mimeType fileName:#""];
NSLog(#"data was loaded.......");
// Present mail view controller on screen
[self presentViewController:mc animated:YES completion:nil];
When ever the program gets the the emailing section it throws a nil exception for addAttachmentData:pdfData mimeType:mimeType fileName: saying the variable I gave it was nil (pdfData) when I know the file exists in the documents directory.
Thanks in advance

plz use this code
- (IBAction)sendMailWithAttachedFile
{
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
// NSURL* outputURL = [[NSURL alloc] initFileURLWithPath:[self pathForResourse:fileName ofType:extension]];
//Get the file path
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"data.pdf"];
NSURL* outputURL = [[NSURL alloc] initFileURLWithPath:path];
NSData *data=[[NSData alloc]initWithContentsOfURL:outputURL];
[picker addAttachmentData:data mimeType:#"application/pdf" fileName:#"data.pdf"];
[self presentModalViewController:picker animated:YES];
}
-(void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
[self dismissViewControllerAnimated:YES completion:nil];
}

Here is how we did it.....
NSString *path = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory,NSUserDomainMask, YES);
documentsDirectory = [paths objectAtIndex:0];
path = [[NSBundle mainBundle]pathForResource:#"Name of File" ofType:#"pdf"];
NSData *pdfData = [NSData dataWithContentsOfFile:path];
MFMailComposeViewController *mail = [[MFMailComposeViewController alloc] init];
mail.editing = YES;
mail.mailComposeDelegate = self;
[mail setSubject:#"Your subject"];
[pdfData writeToFile:path atomically:NO];
[mail addAttachmentData:pdfData mimeType:#"application/pdf" fileName:#"Name OF File.pdf"];
[self presentViewController:mail animated:YES completion:NULL];

Related

UIButton's IBAction only works the first time it is tapped

Using Apple's template "Tabbed Bar Banner" I found that the button in one of the views only works the first times I pressed it.
If the iPhone is connected to Xcode to run the app, it works great. Once I have detached the cable, the button stops working.
- (IBAction)sendData:(id)sender {
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
imagePicker.allowsEditing = YES;
[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:#"*******", nil]];
[mailComposer setSubject:self.nameTextField.text];
NSLog(#"self.nameTextField.text = %#", *********);
[mailComposer setMessageBody:#"******r" 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, 0.5);
[mailComposer addAttachmentData:imageData mimeType:#"image/jpg" fileName:[NSString stringWithFormat:#"%#.jpg",*********]];
[self composeCSV];
NSString *fileName = [file lastPathComponent];
[mailComposer addAttachmentData:[NSData dataWithContentsOfFile:file] mimeType:#"text/csv" fileName:fileName];
[self presentViewController:mailComposer animated:YES completion:nil];
}
}
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)composeCSV{
NSMutableString *mainString = [[ NSMutableString alloc]initWithString:#"++;++;++;++;...\n"];
[mainString appendFormat:#"%#;\n",...];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
file = [NSString stringWithFormat:#"%#/%#.csv",documentsDirectoryPath,******];
NSError *csVerror= NULL;
BOOL written = [mainString writeToFile:file atomically:YES encoding:NSUTF8StringEncoding error:&csVerror];
if (!written) {
NSLog( #"Writing failed, error = %#",csVerror);
}else {
NSLog(#"Data saved! File path = %#",file);
}
}

Unable to attach text file to email

I am trying to generate a text file and attach it to email. Previously I used this code to attach the file to email and it is done successfully.
NSString *recipient = #"myemail#me.com";
NSArray *recipients = [NSArray arrayWithObjects:recipient, nil];
MFMailComposeViewController *mailViewController = [[MFMailComposeViewController alloc] init];
mailViewController.mailComposeDelegate = self;
[mailViewController setSubject:#"Invalid Scan"];
[mailViewController setToRecipients:recipients];
[mailViewController setMessageBody:#"" isHTML:NO];
mailViewController.navigationBar.tintColor = [UIColor blackColor];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *textFilePath = [documentsDirectory stringByAppendingFormat:#"/textfile.txt"];
NSData *myData = [NSData dataWithContentsOfFile:textFilePath];
// NSLog(#"my nsdata is %#",myData);
[mailViewController addAttachmentData:myData
mimeType:#"text/csv"
fileName:textfile.txt];
But when I tried to use this statement below ,the file didn't get attached :
NSString *fileName_txtFile= #"textfile.txt";
NSString *textFilePath = [documentsDirectory stringByAppendingFormat:[NSString stringWithFormat:#"/%#",fileName_txtFile],nil];
NSData *myData = [NSData dataWithContentsOfFile:textFilePath];
[mailViewController addAttachmentData:myData
mimeType:#"text/csv"
fileName:fileName_txtFile];
I couldn't figure out, why the file is not attaching to the mail. Could you please help me in this issue?
Thanks in advance!!

ios sending email with no attachment

I have implemented the module for sending the email from my iPhone device to server. When it comes to the implementation, there is no email file attach instead. I sweared I have added the attACHMENT . THE below is my working
-(IBAction)sendMail:(id)sender{
NSArray *toRecipents = [NSArray arrayWithObjects:#"birth.lo#sdsdfsfsdf-hk.com",#"jason.li#asdasdad-hk.com",#"lo.sdad#gmail.com",nil];
mailComposer = [[MFMailComposeViewController alloc]init];
if ([MFMailComposeViewController canSendMail]) {
mailComposer.mailComposeDelegate = self;
[mailComposer setSubject:#"NOXAV testing"];
[mailComposer setToRecipients:toRecipents] ;
[mailComposer setMessageBody:#"Testing message for the test mail" isHTML:NO];
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//make a file name to write the data to using the documents directory:
NSString *fileName = [NSString stringWithFormat:#"%#/textfile.txt",
documentsDirectory];
NSData *fileData = [NSData dataWithContentsOfFile:fileName];
NSString *mimeType = #"text/html";
[mailComposer addAttachmentData:fileData mimeType:mimeType fileName:fileName];
[self presentModalViewController:mailComposer animated:YES ];
}
}
-(void)mailComposeController:(MFMailComposeViewController *)controller
didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error{
if (result) {
NSLog(#"Result : %d",result);
}
if (error) {
NSLog(#"Error : %#",error);
}
[self dismissModalViewControllerAnimated:YES];
}
The MIME type for text file should be text/plain,So change
NSString *mimeType = #"text/html";
to
NSString *mimeType = #"text/plain";
Edit
Also change the fileName here
[mailComposer addAttachmentData:fileData mimeType:mimeType fileName:#"textfile.txt"];
Looks like file name problem, change following statement along with above suggested by Yogesh -
//make a file name to write the data to using the documents directory:
NSString * fileName = [documentsDirectory stringByAppendingPathComponent:#"textfile.txt"];
NSData *fileData = [NSData dataWithContentsOfFile:fileName];
NSString *mimeType = #"text/plain";
Your fileData may not be getting the data from file. Check if [filedata length] = some value.

Add [self screenshot]; as email attachment?

I would like to add [self screenshot]; to my mail function as attachment. How can I do this without saving the image to the photo library? Here´s my code in ViewController.m:
Screenshot Function:
- (UIImage *)screenshot
{
UIImage *backgroundImage = [UIImage imageNamed:#"iphoneframe.png"];
UIGraphicsBeginImageContext(backgroundImage.size);
[backgroundImage drawInRect:CGRectMake(0, 0, backgroundImage.size.width, backgroundImage.size.height)];
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
[screenshot drawInRect:CGRectMake(backgroundImage.size.width - screenshot.size.width, backgroundImage.size.height - screenshot.size.height, screenshot.size.width, screenshot.size.height)];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
E-Mail Function:
- (void)sendMail
{
if ([MFMailComposeViewController canSendMail]){
MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];
mailer.mailComposeDelegate = self;
[mailer setSubject:#"Mein Punktestand bei KlickMich"];
//Attachement Object
UIImage *myImage = [UIImage imageNamed:#"image.jpg"];
NSData *imageData = UIImagePNGRepresentation(myImage);
[mailer addAttachmentData:imageData mimeType:#"image/jpg" fileName:#"image.jpg"];
NSString *messageBody = [NSString stringWithFormat:#"Hey, habe gerade ganze %i Punkte innerhalb von nur 15 Sekunden in der KlickMich App erreicht. Kannst du es besser?<br /><br />-> <a href='http://appstore.com/KlickMich'>appstore.com/KlickMich</a>",count];
[mailer setMessageBody:messageBody isHTML:YES];
[self presentViewController:mailer animated:YES completion:NULL];
}
[…]
Yours faithfully
Robin
When you take a screenshot that time you have to save your image in DocumentDirectory like this :
NSArray *path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *imagePath=[path objectAtIndex:0];
NSFileManager *fileManager = [NSFileManager defaultManager] ;
BOOL isDir ;
imagePath =[imagePath stringByAppendingPathComponent:#"MyImage"];
if(YES == [fileManager fileExistsAtPath:imagePath isDirectory:&isDir])
{
}
else
{
[fileManager createDirectoryAtPath:imagePath withIntermediateDirectories:NO attributes:nil error:nil];
}
imagePath =[imagePath stringByAppendingPathComponent:#"Image.jpg"];
NSData *tempImageData=[NSData dataWithData:UIImagePNGRepresentation(viewImage)];
[tempImageData writeToFile:imagePath atomically:YES];
When you want to share that image you have to retrieve that image from DocumentDirectory & share it.
NSFileManager *fileManager = [NSFileManager defaultManager] ;
NSArray *path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *imagePath=[path objectAtIndex:0];
imagePath =[imagePath stringByAppendingPathComponent:#"MyImage"];
NSArray *temp=[fileManager contentsOfDirectoryAtPath:imagePath error:nil];
NSString *tempImgPath = [imagePath stringByAppendingPathComponent:[temp objectAtIndex:0]];
NSData *imgData = [NSData dataWithContentsOfFile:tempImgPath];
MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];
mailer.mailComposeDelegate = self;
[mailer setSubject:#"Mein Punktestand bei KlickMich"];
[mailer addAttachmentData:imgData mimeType:#"image/jpg" fileName:#"image.jpg"];
NSString *messageBody = [NSString stringWithFormat:#"Hey, habe gerade ganze %i Punkte innerhalb von nur 15 Sekunden in der KlickMich App erreicht. Kannst du es besser?<br /><br />-> <a href='http://appstore.com/KlickMich'>appstore.com/KlickMich</a>",count];
[mailer setMessageBody:messageBody isHTML:YES];
[self presentViewController:mailer animated:YES completion:NULL];

iOS: file name in email attachment

I can send a .csv file as an attachment from my app, but I'd like to shorten the name file for that attachment, because there will be a pile of csv files delivered to the recipient.
Piece of code:
...
if (dorsalesPorTramoYcontrol && dorsalesPorTramoYcontrol.count )
{
NSMutableString *mainString = [[ NSMutableString alloc]initWithString:#"dorsal,paso,tiempo\n"];
for (NSManagedObject *get in dorsalesPorTramoYcontrol) {
//dorsales
NSString *string =[get valueForKey:#"dorsal"];
[mainString appendFormat:#"%#,",string];
//paso
string = [get valueForKey:#"paso"];
string=[string stringByReplacingOccurrencesOfString:#"\"" withString:#"\"\""];
[mainString appendFormat:#"%#,",string];
//tiempo
string = [get valueForKey:#"tiempo"];
string=[string stringByReplacingOccurrencesOfString:#"\"" withString:#"\"\""];
[mainString appendFormat:#"%#",string];
[mainString appendFormat:#"\n"];
}
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
file = [NSString stringWithFormat:#"%#/Tramo%#Control%#.csv", documentsDirectoryPath,section,control];
NSError *csVerror= NULL;
BOOL written = [mainString writeToFile:file atomically:YES encoding:NSUTF8StringEncoding error:&csVerror];
if (!written) {
NSLog( #"Writing failed, error = %#",csVerror);
}else {
NSLog(#"Data saved! File path = %#",file);
[self composeEmail];
}
}
}
-(void)composeEmail{
if ([MFMailComposeViewController canSendMail])
{
MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];
mailer.mailComposeDelegate = self;
[mailer setSubject:[NSString stringWithFormat:#"Resultados Tramo: %# - Control: %#", section, control]];
NSArray *toRecipients = [NSArray arrayWithObjects:#"somebodymail#mail.com", nil];
[mailer setToRecipients:toRecipients];
// Logo
UIImage *myImage = [UIImage imageNamed:#"logo.png"];
NSData *imageData = UIImagePNGRepresentation(myImage);
[mailer addAttachmentData:imageData mimeType:#"image/png" fileName:#"Icon"];
[mailer addAttachmentData:[NSData dataWithContentsOfFile:file] mimeType:#"text/csv" fileName:file];
NSString *emailBody =
[NSString stringWithFormat:#"Resultados Tramo: %# - Control: %# \nDorsal - Paso - Tiempo", section, control];
[mailer setMessageBody:emailBody isHTML:NO];
mailer.modalPresentationStyle = UIModalPresentationPageSheet;
[self presentViewController:mailer animated:YES completion:nil];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Failure"
message:#"Your device doesn't support the composer sheet"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[alert show];
}
}
The filename is the following:
<_var_mobile_Applications_BE8CE610-A83E-4C79-8B9C-0263FA6881D6_Documents_Tramo2Control4.csv>
and I'd like it to be just "Tramo2Control4.csv"
Could you please offer some suggestions to get it?
Change the following line:
[mailer addAttachmentData:[NSData dataWithContentsOfFile:file] mimeType:#"text/csv" fileName:file];
To:
NSString *fileName = [file lastPathComponent];
[mailer addAttachmentData:[NSData dataWithContentsOfFile:file] mimeType:#"text/csv" fileName:fileName];
You were originally setting the file name to be the entire file path.

Resources