I am having a problem either attaching or creating a .csv file in my app, I cannot figure out where the problem exists. In the email view the .csv attachment is shown but when the email is received it has no attachment. I send an array of objects (dataController.masterList) to the CHCSVWriter. I've spent a lot of time this week trying solutions from other questions regarding email attachments and CHCSVWriter and obviously none of the solutions have worked so know I'm asking you. Where does the problem exist, and what do you suggest?
Thank you in advance,
Happy Days, -Rob
- (IBAction)send:(id)sender {
static NSDateFormatter *formatter = nil;
if (formatter == nil) {
formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterMediumStyle];
}
NSString *filepath = #"testfile.csv";
filepath = [filepath stringByExpandingTildeInPath];
NSOutputStream *exportStream = [NSOutputStream outputStreamToFileAtPath:filepath append:NO];
NSStringEncoding encodingA = NSUTF8StringEncoding;
CHCSVWriter *csvWriter = [[CHCSVWriter alloc] initWithOutputStream:exportStream encoding:encodingA delimiter:','];
[csvWriter writeField:[NSString stringWithFormat:#"One"]];
[csvWriter writeLineOfFields:dataController.masterList];
[csvWriter closeStream];
NSString *path = [[NSBundle mainBundle] pathForResource:filepath ofType:#".csv"];
NSData *mydata = [NSData dataWithContentsOfFile:path];
if ([MFMailComposeViewController canSendMail]) {
MFMailComposeViewController *mail = [[MFMailComposeViewController alloc] init];
[mail setMailComposeDelegate:self];
[mail setSubject:#"CSV File"];
[mail addAttachmentData:mydata mimeType:#"text/csv" fileName:filepath];
[mail setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
[self presentViewController:mail animated:YES completion:nil];
}
}
- (void)mailComposeController:(MFMailComposeViewController *)controller
didFinishWithResult:(MFMailComposeResult)result
error:(NSError *)error {
[self dismissViewControllerAnimated:YES completion:nil];
I figured it out, I stopped using the CHCSV writer and just wrote an array then combined the components of the array with a ",".
- (IBAction)send:(id)sender {
static NSDateFormatter *formatter = nil;
if (formatter == nil) {
formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterMediumStyle];
}
NSIndexPath *index2 = 0;
NSUInteger i = 0;
NSString *holder;
NSArray *holderArray;
NSArray *saverArray;
while (i < dataController.countOfList) {
TimeSheetEntry *sAtIndex = [self.dataController objectInListAtIndex:index2.row];
NSString *dayhold = [formatter stringFromDate:sAtIndex.date];
holderArray = [[NSArray alloc] initWithObjects:sAtIndex.name, sAtIndex.jobnum, sAtIndex.hours, sAtIndex.jobnotes, dayhold, nil];
saverArray = [saverArray arrayByAddingObjectsFromArray:holderArray];
i++;
NSIndexPath *index3 = [NSIndexPath indexPathForRow:i inSection:1];
index2 = index3;
}
holder = [saverArray componentsJoinedByString:#","];//this is the seperating variable
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDirectory = [paths objectAtIndex:0];
NSString *outputFile = [docDirectory stringByAppendingPathComponent:#"timesheet.csv"];
NSError *csvError = NULL;
BOOL written = [holder writeToFile:outputFile atomically:YES encoding:NSUTF8StringEncoding error:&csvError];
if (!written)
NSLog(#"write failed, error=%#", csvError);
if ([MFMailComposeViewController canSendMail]) {
MFMailComposeViewController *mail = [[MFMailComposeViewController alloc] init];
[mail setMailComposeDelegate:self];
[mail setSubject:#"CSV File"];
//[mail setMessageBody:holder isHTML:YES];
[mail addAttachmentData:[NSData dataWithContentsOfFile:outputFile] mimeType:#"text/csv" fileName:#"timesheet.csv"];
[mail setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
[self presentViewController:mail animated:YES completion:nil];
}
}
- (void)mailComposeController:(MFMailComposeViewController *)controller
didFinishWithResult:(MFMailComposeResult)result
error:(NSError *)error {
[self dismissViewControllerAnimated:YES completion:nil];
}
#end
For anyone that still wants to use CHCSVParser, I found that the file path has to be absolute:
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Task"
inManagedObjectContext:_tempManagedObjectContext];
[fetchRequest setEntity:entity];
NSError *error;
NSArray *fetchedObjects = [_tempManagedObjectContext executeFetchRequest:fetchRequest error:&error];
NSURL *datapath = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"export.csv"];
NSOutputStream *output = [NSOutputStream outputStreamToMemory];
CHCSVWriter *writer = [[CHCSVWriter alloc] initWithOutputStream:output encoding:NSUTF8StringEncoding delimiter:','];
// Fetch objects to write to .csv
for (Task *task in fetchedObjects) {
[writer writeLineOfFields:#[task.taskID, task.taskTitle, task.taskDescription]];
}
entity = [NSEntityDescription entityForName:#"Journal"
inManagedObjectContext:_tempManagedObjectContext];
[fetchRequest setEntity:entity];
fetchedObjects = [_tempManagedObjectContext executeFetchRequest:fetchRequest error:&error];
for (JournalEntry *entry in fetchedObjects) {
[writer writeLineOfFields:#[entry.day, entry.entryTitle, entry.entryDescription]];
}
[writer closeStream];
NSData *buffer = [output propertyForKey:NSStreamDataWrittenToMemoryStreamKey];
[buffer writeToURL:datapath atomically:NO];
Related
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];
I am trying to send a CSV file through MfMail Composer.Everything works fine but there are lot leaks while using Instruments.I am not able trace out where I went wrong.Here is my code.
-(NSData *)getCSV
{
NSManagedObjectContext *moc = [(ETAppDelegate *)[[UIApplication sharedApplication] delegate]managedObjectContext];
NSFetchRequest *request = [[[NSFetchRequest alloc]init]autorelease];
[request setEntity:[NSEntityDescription entityForName:#"Expense" inManagedObjectContext:moc]];
NSError *error = nil;
NSArray *results = [moc executeFetchRequest:request error:&error];
NSMutableArray *expensesList = [[[NSMutableArray alloc]init]autorelease];
for(int i = 0;i<[results count];i++){
NSString *category = [[results objectAtIndex:i]valueForKey:#"category"];
NSString *date = [[NSDateFormatter dateFormatterwithMediumStyle]stringFromDate:[[results objectAtIndex:i]valueForKey:#"date"]];
NSString *amount = [NSNumberFormatter localizedStringFromNumber:[[results objectAtIndex:i]valueForKey:#"amount"] numberStyle:NSNumberFormatterCurrencyStyle];
NSString *mailString = [NSString stringWithFormat:#"%#,%#,%#",category,date,amount ];
[expensesList addObject:mailString];
}
NSString *expensesString = [expensesList componentsJoinedByString:#"\n"];
NSData *expensesData = [expensesString dataUsingEncoding:NSUTF8StringEncoding];
return expensesData;
}
-(void)displayComposerSheet
{
NSData *csvFile = [self getCSV];
NSString *csvFileName = #"MyExpenses";
MFMailComposeViewController *mailController = [[MFMailComposeViewController alloc]init];
[mailController setSubject:#"List Of Expenses"];
[mailController setMessageBody:#"Expenses" isHTML:NO];
[mailController addAttachmentData:csvFile mimeType:#"text/csv" fileName:csvFileName];
[mailController setMailComposeDelegate:self];
[self presentModalViewController:mailController animated:YES];
[mailController release];
}
I can't say that I see anything in the code you've provided that should cause you to leak. Your leaks are likely taking place elsewhere.
What I do see, however, is the potential to create a lot of autoreleased objects in that loop in -getCSV, and depending on how many iterations you're performing, that could be almost as bad. The way you've written it, I see a date formatter and three strings headed for your main autorelease pool with every iteration. One suggestion is to create a date formatter outside your loop that you can reuse inside it. Another suggestion is to frame the guts of your loop with a local autorelease pool; that will prevent your main autorelease pool from becoming too large.
Apropos of nothing, you should also consider using fast enumeration.
Here's your loop with the suggestions applied:
NSDateFormatter *myDateFormatter = [NSDateFormatter dateFormatterWithMediumStyle];
NSMutableArray *expensesList = [[[NSMutableArray alloc] init] autorelease];
for (id obj in results)
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *category = [obj valueForKey:#"category"];
NSString *date = [myDateFormatter stringFromDate:[obj valueForKey:#"date"]];
NSString *amount = [NSNumberFormatter localizedStringFromNumber:[obj valueForKey:#"amount"] numberStyle:NSNumberFormatterCurrencyStyle];
NSString *mailString = [NSString stringWithFormat:#"%#,%#,%#", category, date, amount];
[expensesList addObject:mailString];
[pool release];
}
I have training app i want that when user click recordVideo button camera should launch to record video, is there any way to do this in ipad app.I have done audio recording already i need to do video recording.
//for video..
#import <MobileCoreServices/MobileCoreServices.h>
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/Mediaplayer.h>
#import <CoreMedia/CoreMedia.h>
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
{
NSArray *mediaTypes = [NSArray arrayWithObject:(NSString*)kUTTypeMovie];
picker.mediaTypes = mediaTypes ;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
picker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModeVideo ;
[self presentModalViewController:picker animated:NO];
[picker release];
}
else
{
UIAlertView *alt=[[UIAlertView alloc]initWithTitle:#"Error" message:#" Camera Facility is not available with this Device" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alt show];
[alt release];
}
for saving into Document folder & it also save in photo Library
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
//for video
NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSLog(#"video url-%#",videoURL);
NSData *videoData = [NSData dataWithContentsOfURL:videoURL];
NSString * videoName = [NSString stringWithFormat:#"student_%d_%d.mp4",stud_id,imgVidID];
videoPath = [documentsDirectory stringByAppendingPathComponent:videoName];
NSLog(#"video path-%#",videoPath);
[videoData writeToFile:videoPath atomically:YES];
NSString *sourcePath = [[info objectForKey:#"UIImagePickerControllerMediaURL"]relativePath];
UISaveVideoAtPathToSavedPhotosAlbum(sourcePath,nil,nil,nil);
}
Try this ::
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary*)info
{
[self dismissViewControllerAnimated:NO completion:nil];
NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
if ([type isEqualToString:(NSString *)kUTTypeVideo] || [type isEqualToString:(NSString *)kUTTypeMovie])
{
videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSLog(#"found a video");
// Code To give Name to video and store to DocumentDirectory //
videoData = [[NSData dataWithContentsOfURL:videoURL] retain];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSDateFormatter *dateFormat = [[[NSDateFormatter alloc] init] autorelease];
[dateFormat setDateFormat:#"dd-MM-yyyy||HH:mm:SS"];
NSDate *now = [[[NSDate alloc] init] autorelease];
theDate = [dateFormat stringFromDate:now];
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"Default Album"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:nil];
NSString *videopath= [[[NSString alloc] initWithString:[NSString stringWithFormat:#"%#/%#.mov",documentsDirectory,theDate]] autorelease];
BOOL success = [videoData writeToFile:videopath atomically:NO];
NSLog(#"Successs:::: %#", success ? #"YES" : #"NO");
NSLog(#"video path --> %#",videopath);
}
}
Hopefully, It'll help you.
Thanks.
Just try it :
-(void) imagePickerController: (UIImagePickerController *) picker didFinishPickingMediaWithInfo: (NSDictionary *) info
{
NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
[self dismissModalViewControllerAnimated:NO];
NSString *moviePath = [[info objectForKey: UIImagePickerControllerMediaURL] path];
if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum (moviePath)){
UISaveVideoAtPathToSavedPhotosAlbum (moviePath,self, #selector(video:didFinishSavingWithError:contextInfo:), nil);
}
}
-(void)video:(NSString*)videoPath didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextInfo {
if (error) {
[AJNotificationView showNoticeInView:self.view type:AJNotificationTypeRed title:#"Video Saving Failed" linedBackground:AJLinedBackgroundTypeAnimated hideAfter:1.0];
}
else{
NSURL *videoURl = [NSURL fileURLWithPath:videoPath];
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURl options:nil];
AVAssetImageGenerator *generate = [[AVAssetImageGenerator alloc] initWithAsset:asset];
generate.appliesPreferredTrackTransform = YES;
NSError *err = NULL;
CMTime time = CMTimeMake(1, 60);
CGImageRef imgRef = [generate copyCGImageAtTime:time actualTime:NULL error:&err];
self.strUploadVideoURL = videoPath;
[imgPhoto setImage:[[[UIImage alloc] initWithCGImage:imgRef] autorelease]];
intWhenPushView = 2;
btnShare.enabled = YES;
btnFacebookShare.enabled = YES;
CGImageRelease(imgRef);
[generate release];
[asset release];
}
}
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
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];