how to zip and email a file using objective c? - objective-c

I need to zip my log file and email it. I'm using Objective-zip for zipping my file. And this is my code
-(void)mailLogFile {
if ([MFMailComposeViewController canSendMail]) {
NSDictionary *user = [[DBHelper getSharedInstance] getCurrentUser];
NSString *propertyQuery = [NSString stringWithFormat:#"SELECT RecentActivityId,PropertyPIC,PropertyId,Message,IsSynced,ActivityTime,ErrorCode,ErrorMessage,ErrorData,EntityId,TableNames From RecentActivity ORDER BY ActivityTime desc"];
NSArray *resultArry = [[DBHelper getSharedInstance] getRecordsBySQL:propertyQuery];
NSLog(#"This is the eNVDS in Recent Activity:%#" ,resultArry);
[[DBHelper getSharedInstance] AddLogFile:[NSString stringWithFormat:#"This is the eNVDS in Recent Activity:%#" ,resultArry]];
NSPredicate *notsynced = [NSPredicate predicateWithFormat:#"IsSynced == 0 || IsSynced == %#",#"0"];
NSArray *notsyncedenvds = [resultArry filteredArrayUsingPredicate:notsynced];
NSLog(#"This is the eNVDS in Recent Activity which is not synced:%#" ,notsyncedenvds);
[[DBHelper getSharedInstance] AddLogFile:[NSString stringWithFormat:#"This is the eNVDS in Recent Activity which is not synced:%#" ,notsyncedenvds]];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *WritableDBPath= [documentsDirectory stringByAppendingPathComponent:#"Logfile.txt"];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"test.zip"];
NSData *zipdata = [NSData dataWithContentsOfFile:path];
NSData *data = [NSData dataWithContentsOfFile:WritableDBPath];
//OZZipFile *readFile = [[OZZipFile alloc] initWithFileName:path mode:OZZipFileModeCreate];
OZZipFile *zipFile32= [[OZZipFile alloc] initWithFileName:path mode:OZZipFileModeCreate];
OZZipWriteStream *stream= [zipFile32 writeFileInZipWithName:#"Logfile.txt" compressionLevel:OZZipCompressionLevelBest];
[stream writeData:data];
[stream finishedWriting];
NSString *emailTitle = [NSString stringWithFormat:#"Log file of %#",[NSDate date]];
NSMutableString *messageBody = [NSMutableString stringWithFormat:#"Login with %#",user[#"Username"]];
if(![user[#"PropertyName"] isKindOfClass:[NSNull class]])[messageBody appendFormat:#"\n%#",user[#"PropertyName"]];
[messageBody appendFormat:#"\nApp version : %#",APP_VERSION];
[messageBody appendFormat:#"\nPlease describe your problem scenario here."];
[messageBody appendFormat:#"\n\n\nThanks"];
NSArray *toRecipents = [NSArray arrayWithObject:#"support#aglive.com"];
MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
mc.mailComposeDelegate = self;
[mc setSubject:emailTitle];
[mc setMessageBody:messageBody isHTML:NO];
[mc setToRecipients:toRecipents];
[mc addAttachmentData:zipdata mimeType:#"application/zip" fileName:#"test.zip"];
[self presentViewController:mc animated:YES completion:nil];
[zipFile32 close];
}else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Aglive Pro" message:#"You have not configured your mail account. Please configure your mail account from the device settings." delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
}
}
right now I'm able to send a zip file in email but when I do unzip and open the file in my mobile or mac I get alert saying that The document “Logfile 4.txt” could not be opened. The file isn’t in the correct format. I don't know where I'm going wrong.

This code worked for me
-(void)mailLogFile {
if ([MFMailComposeViewController canSendMail]) {
NSDictionary *user = [[DBHelper getSharedInstance] getCurrentUser];
NSString *propertyQuery = [NSString stringWithFormat:#"SELECT RecentActivityId,PropertyPIC,PropertyId,Message,IsSynced,ActivityTime,ErrorCode,ErrorMessage,ErrorData,EntityId,TableNames From RecentActivity ORDER BY ActivityTime desc"];
NSArray *resultArry = [[DBHelper getSharedInstance] getRecordsBySQL:propertyQuery];
NSLog(#"This is the eNVDS in Recent Activity:%#" ,resultArry);
[[DBHelper getSharedInstance] AddLogFile:[NSString stringWithFormat:#"This is the eNVDS in Recent Activity:%#" ,resultArry]];
NSPredicate *notsynced = [NSPredicate predicateWithFormat:#"IsSynced == 0 || IsSynced == %#",#"0"];
NSArray *notsyncedenvds = [resultArry filteredArrayUsingPredicate:notsynced];
NSLog(#"This is the eNVDS in Recent Activity which is not synced:%#" ,notsyncedenvds);
[[DBHelper getSharedInstance] AddLogFile:[NSString stringWithFormat:#"This is the eNVDS in Recent Activity which is not synced:%#" ,notsyncedenvds]];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *WritableDBPath= [documentsDirectory stringByAppendingPathComponent:#"Logfile.txt"];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"Logfile.zip"];
NSData *zipdata = [NSData dataWithContentsOfFile:path];
NSData *data = [NSData dataWithContentsOfFile:WritableDBPath];
OZZipFile *zipFile32= [[OZZipFile alloc] initWithFileName:path mode:OZZipFileModeCreate];
//NSData *zipdata2 = [NSData dataWithContentsOfFile:zipFile32];
OZZipWriteStream *stream= [zipFile32 writeFileInZipWithName:#"LogFile.txt" compressionLevel:OZZipCompressionLevelBest];
[stream writeData:data];
[stream finishedWriting];
[zipFile32 close];
NSString *emailTitle = [NSString stringWithFormat:#"Log file of %#",[NSDate date]];
NSMutableString *messageBody = [NSMutableString stringWithFormat:#"Login with %#",user[#"Username"]];
if(![user[#"PropertyName"] isKindOfClass:[NSNull class]])[messageBody appendFormat:#"\n%#",user[#"PropertyName"]];
[messageBody appendFormat:#"\nApp version : %#",APP_VERSION];
[messageBody appendFormat:#"\nPlease describe your problem scenario here."];
[messageBody appendFormat:#"\n\n\nThanks"];
NSArray *toRecipents = [NSArray arrayWithObject:#"support#aglive.com"];
MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
mc.mailComposeDelegate = self;
[mc setSubject:emailTitle];
[mc setMessageBody:messageBody isHTML:NO];
[mc setToRecipients:toRecipents];
//
if(zipdata== 0 && zipdata==nil)
{
[self mailLogFile];
}
else
{
[mc addAttachmentData:zipdata mimeType:#"application/zip" fileName:#"Logfile.zip"];
[self presentViewController:mc animated:YES completion:nil];
}

Related

How do I generate thumbnail of map using given Lat/Long in iOS?

I am working on a chat application where I am going to send a map to another user.
Below is my code to generate a thumbnail of a map. Is there any way to generate a map thumbnail in Objective-C?
Code to generate thumbnail of static map:
NSString *staticMapUrl = [NSString stringWithFormat:#"http://maps.google.com/maps/api/staticmap?markers=color:blue|%#,%#&%#&sensor=true",_lat, _longi,#"zoom=13&size=%dx%d"];
NSURL *mapUrl = [NSURL URLWithString:[staticMapUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
UIImage *Mapimage = [UIImage imageWithData: [NSData dataWithContentsOfURL:mapUrl]];
Save thumbnail images in document directories:
NSString *datapathMap=[Locations stringByAppendingPathComponent:[NSString stringWithFormat:#"Sm_%#_lc_%#.jpg",userid,dateString1]];
NSData *urlData = [NSData dataWithContentsOfURL:mapUrl];
datapathMap = [datapathMap stringByStandardizingPath];
[urlData writeToFile:datapathMap atomically:YES];
Send thumbnail data to bubble to display thumbnail:
NSBubbleData *MapSendBubble = [NSBubbleData dataWithImage:mapImage date:[NSDate date] type:BubbleTypeMine];
MapSendBubble.avatar = [UIImage imageNamed:#"avatar1.png"];
[bubbleData addObject:MapSendBubble];
[_bubbleTable reloadData];
Send map:
NSDate *today=[NSDate date];
NSDateFormatter *dateFormat1 = [[NSDateFormatter alloc] init];
[dateFormat1 setDateFormat:#"YYYYMMddhhmmss"];
NSString *dateString1=[dateFormat1 stringFromDate:today];
NSString *userid= #"mc1"; NSString *latlong=[NSString stringWithFormat:#"%#%#",[_lat substringToIndex:2],[_longi substringToIndex:2]];
[map setTag:[[NSString stringWithFormat:#"%#",latlong] integerValue]];
NSString *longlat=[NSString stringWithFormat:#"%#,%#",_longi,_lat];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd-MMM-yy HH:mm:ss"];
NSString *date=[dateFormat stringFromDate:[NSDate date]];
//Find a cache directory. You could consider using documents dir instead (depends on the data you are fetching)
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
NSError *error;
NSString *MainFolder = [path stringByAppendingPathComponent:[NSString stringWithFormat:#"/SmoothChat"]];
NSString *Locations=[MainFolder stringByAppendingPathComponent:[NSString stringWithFormat:#"/Locations"]];
if (![[NSFileManager defaultManager] fileExistsAtPath:MainFolder])
{
[[NSFileManager defaultManager] createDirectoryAtPath:MainFolder withIntermediateDirectories:NO attributes:nil error:&error];
}
if (![[NSFileManager defaultManager] fileExistsAtPath:Locations])
{
[[NSFileManager defaultManager] createDirectoryAtPath:Locations withIntermediateDirectories:NO attributes:nil error:&error];
}
NSString *staticMapUrl = [NSString stringWithFormat:#"http://maps.google.com/maps/api/staticmap?markers=color:red|%#,%#&%#&sensor=true",_lat,_longi,#"zoom=15&size=300x180"];
NSURL *mapUrl = [NSURL URLWithString:[staticMapUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
UIImage *Mapimage = [UIImage imageWithData: [NSData dataWithContentsOfURL:mapUrl]];
NSString *datapathMap=[Locations stringByAppendingPathComponent:[NSString stringWithFormat:#"Sm_%#_lc_%#.jpg",userid,dateString1]];
NSData *urlData = [NSData dataWithContentsOfURL:mapUrl];
datapathMap = [datapathMap stringByStandardizingPath];
[urlData writeToFile:datapathMap atomically:YES];
// NSString *uuid1 = [[NSUUID UUID] UUIDString];
// [self sendXMPPMessage:1 :[NSString stringWithFormat:#"lc%#",value] :[NSString stringWithFormat:#"oi_%#_lc_%#.jpg",userid,dateString1] :#"" :jsonstring :[NSString stringWithFormat:#"%#",longlat] :_user :#"" :#"" :#"" :[[NSUserDefaults standardUserDefaults] stringForKey:#"current_chat"] :#"" :#"" :_senderType :[self currentDateTme] :0];
NSBubbleData *photoBubble11 = [NSBubbleData dataWithImage:staticMapUrl date:[NSDate date] type:BubbleTypeMine];
photoBubble11.avatar = [UIImage imageNamed:#"avatar1.png"];
[bubbleData addObject:photoBubble11];
[_bubbleTable reloadData];
[self goToBottom];
[map setHidden:YES];
[blurView setHidden:YES];
[_NewView setHidden:YES];
[map removeAnnotation:point];
currentLocation=nil;
[locationManager stopUpdatingLocation];

Download sqlite database from URL

I'm using this code the load the local sqlite database.
- (id)init
{
self = [super init];
if (self) {
NSString *path = [[NSBundle mainBundle] pathForResource:#"db" ofType:#"sqlite3"];
_db = [[MDDatabase alloc] initWithPath:path];
_HTMLRenderer = [[MDHTMLRenderer alloc] init];
}
return self;
}
I would like to put the database online and let the app download the database instead. I changed the code to:
NSData *dbFile = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:#"http://www.someurl.com/DatabaseName.sqlite"]];
NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:#"Documents"]];
NSString *filePath = [resourceDocPath stringByAppendingPathComponent:#"Database.sqlite"];
[dbFile writeToFile:filePath atomically:YES];
_db = [[MDDatabase alloc] initWithPath:filePath];
_HTMLRenderer = [[MDHTMLRenderer alloc] init];
Editted:
I changed my code to follow but it's crashed.
- (id)init
{
self = [super init];
if (self) {
[self performSelectorOnMainThread:#selector(downalod) withObject:nil waitUntilDone:YES];
NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:#"Documents"]];
NSString *filePath = [resourceDocPath stringByAppendingPathComponent:#"Database.sqlite"];
_db = [[MDDatabase alloc] initWithPath:filePath];
_HTMLRenderer = [[MDHTMLRenderer alloc] init];
}
return self;
}
-(void)download
{
NSData *dbFile = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:#"http://www.someurl.com/DatabaseName.sqlite"]];
NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:#"Documents"]];
NSString *filePath = [resourceDocPath stringByAppendingPathComponent:#"Database.sqlite"];
[dbFile writeToFile:filePath atomically:YES];
}
You have problem in your file. Check with correct url. Its an encoding issue. Try with this (It will work) : http://spaceflight.nasa.gov/gallery/images/apollo/apollo17/hires/s72-55482.jpg
Add App Transport Security Settings (Allow Arbitrary Loads YES) in your plist.
Enable background mode.
Declare this macro in .m
#define DocumentsDirectory [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]
Now call and you will have the file in your local.
Call like:
[self performSelectorOnMainThread:#selector(downalod) withObject:nil waitUntilDone:NO];
_db = [[MDDatabase alloc] initWithPath:filePath];
_HTMLRenderer = [[MDHTMLRenderer alloc] init];
-(void)download
{
NSString *stringURL =[NSString stringWithFormat: #"url"];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#",[stringURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSString *filePath = [DocumentsDirectory stringByAppendingPathComponent:[url lastPathComponent]];
NSLog(#"success--222,%#", filePath);
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
NSLog(#"success--222,%#", filePath);
if (error)
{
NSLog(#"success--not---Error,%#", [error localizedDescription]);
}
else
{
NSLog(#"success--yes... %#", [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]);
[data writeToFile:filePath atomically:YES];
}
}];
}
After long time search, finally I solved it myself:
- (id)init
{
self = [super init];
if (self) {
NSData *fetchedData = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://www.someurl.com/db.sqlite3"]];
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *filePath = [documentsPath stringByAppendingPathComponent:#"db.sqlite3"];
[fetchedData writeToFile:filePath atomically:YES];
_db = [[MDDatabase alloc] initWithPath:filePath];
_HTMLRenderer = [[MDHTMLRenderer alloc] init];
}
return self;
}

How to attach image in vCard (vcf file) using Objective C?

In my project I need to create and send a vCard (vcf file) that must include an image too. I did everything right except I can not add image to the vCard. I have shared my code below.
- (IBAction)shareButtonPressed:(UIButton *)sender {
NSError *error;
NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:#"vCard.vcf"];
[[self vCardRepresentation] writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:#[#"Test", [NSURL fileURLWithPath:filePath]] applicationActivities:nil];
activityVC.excludedActivityTypes = #[UIActivityTypePostToWeibo, UIActivityTypeAssignToContact, UIActivityTypeMessage, UIActivityTypeCopyToPasteboard];
[self presentViewController:activityVC animated:YES completion:^{
}];
}
- (NSString *)vCardRepresentation
{
NSMutableArray *mutableArray = [[NSMutableArray alloc] init];
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:#"Rokon"], 1.0);
[mutableArray addObject:#"BEGIN:VCARD"];
[mutableArray addObject:#"VERSION:3.0"];
[mutableArray addObject:[NSString stringWithFormat:#"FN:%#", #"Rokon"]];
[mutableArray addObject:[NSString stringWithFormat:#"TEL:%#",#"+8801811536248"]];
[mutableArray addObject:[NSString stringWithFormat:#"PHOTO;BASE64:%#",[imageData base64EncodedDataWithOptions:0]]];
[mutableArray addObject:#"END:VCARD"];
return [mutableArray componentsJoinedByString:#"\n"];
}
- (void)shareContact{
[self emptySandbox];
NSString *contactName = [NSString stringWithFormat:#"%# %#",[Person sharedInstance].firstName, [Person sharedInstance].lastName];
NSError *error;
NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.vcf", contactName]];
[[self vCardRepresentation] writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:#[contactName, [NSURL fileURLWithPath:filePath]] applicationActivities:nil];
activityVC.excludedActivityTypes = #[UIActivityTypePostToWeibo, UIActivityTypeAssignToContact, UIActivityTypeCopyToPasteboard];
[activityVC setValue:contactName forKey:#"subject"];
[self presentViewController:activityVC animated:YES completion:^{
}];
}
- (NSString *)vCardRepresentation
{
NSMutableArray *mutableArray = [[NSMutableArray alloc] init];
NSData *imageData = UIImageJPEGRepresentation([Person sharedInstance].profileImage, 1.0);
[mutableArray addObject:#"BEGIN:VCARD"];
[mutableArray addObject:#"VERSION:3.0"];
[mutableArray addObject:[NSString stringWithFormat:#"FN:%#", [NSString stringWithFormat:#"%#%#", [Person sharedInstance].firstName, [Person sharedInstance].lastName]]];
[mutableArray addObject:[NSString stringWithFormat:#"TEL:%#",[Person sharedInstance].phone]];
[mutableArray addObject:[NSString stringWithFormat:#"email:%#", [Person sharedInstance].email]];
[mutableArray addObject:[NSString stringWithFormat:#"PHOTO;BASE64;ENCODING=b;TYPE=JPEG:%#",[imageData base64EncodedStringWithOptions:0]]];
[mutableArray addObject:#"END:VCARD"];
return [mutableArray componentsJoinedByString:#"\n"];
}
-(void)emptySandbox
{
NSFileManager *fileMgr = [[NSFileManager alloc] init];
NSError *error = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *files = [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:nil];
while (files.count > 0) {
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *directoryContents = [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error];
if (error == nil) {
for (NSString *path in directoryContents) {
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:path];
BOOL removeSuccess = [fileMgr removeItemAtPath:fullPath error:&error];
files = [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:nil];
if (!removeSuccess) {
// Error
}
}
} else {
// Error
}
}
}

Email does not attach file

I'm using the below code to send a csv via email. The email is send and I received in my Inbox, but I'm not receiving the csv file attached, any idea about what is wrong?
-(void)generateCSV
{
NSFileManager *filemgr = [NSFileManager defaultManager];
NSArray *dirPaths;
NSString *docsDir;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
if ([filemgr fileExistsAtPath:[NSString stringWithFormat:#"%#/test.csv", docsDir] ] == NO)
{
[filemgr createFileAtPath:[NSString stringWithFormat:#"%#/test.csv", docsDir] contents:[#"" dataUsingEncoding: NSUnicodeStringEncoding] attributes: nil];
}
surveyarray = [db retrieveSurvey];
CHCSVWriter * csvWriter = [[CHCSVWriter alloc] initWithCSVFile:[NSString stringWithFormat:#"%#/test.csv", docsDir] atomic:NO];
NSString *str = [NSString stringWithFormat: #"No, CreatedDate, Question1, Question2, Question3, Comment\n"];
[csvWriter writeField:str];
for(int i = 0; i < surveyarray.count; i++)
{
survey = [surveyarray objectAtIndex:i];
NSString *str = [NSString stringWithFormat: #"%d, %#, %#, %#, %#, %#\n", i, survey.createddate, survey.question1, survey.question2, survey.question3, survey.comment];
[csvWriter writeField:str];
}
NSMutableString *subject = [[NSMutableString alloc] init];
NSMutableString *emailBody = [[NSMutableString alloc] init];
[subject appendString:#""];
MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];
mailer.mailComposeDelegate = self;
[mailer setSubject:subject];
NSArray *toRecipients = [NSArray arrayWithObjects:#"", nil];
[mailer setToRecipients:toRecipients];
NSData *myData = [NSData dataWithContentsOfFile:[NSString stringWithFormat:#"%#/test.csv", docsDir]];
NSLog(#"%#", myData);
[mailer addAttachmentData:myData mimeType:#"text/csv" fileName:#"test.csv"];
[mailer setMessageBody:emailBody isHTML:NO];
mailer.modalPresentationStyle = UIModalPresentationPageSheet;
[self presentModalViewController:mailer animated:YES];
[mailer release];
[subject release];
[emailBody release];
[csvWriter release];
}
I am generating csv file then send email as attachment.
I open the email in my mailbox, it does not content any attachment.
According to what I see there, I'd say that you forgot to add .csv at the end of your filename :)
According to the NSData class reference, the path given with dataWithContentsOfFile: should be the absolute path. So you should use
[NSString stringWithFormat:#"%#/test.csv", docsDir]
instead of just #"test.csv"
I bet currently your myData is nil or empty.
By the way, I would create an NSString object with the fully qualified path/filename only once and re-use that rather than creating it 3 or 4 times.
This code works for me every time!
http://developer.apple.com/library/ios/#samplecode/MailComposer/Introduction/Intro.html#//apple_ref/doc/uid/DTS40008865
try replacing above line this
[mailer addAttachmentData:myData mimeType:#"text/csv" fileName:#"test.csv"];
finally I solved the problem. The email did attached attachment just the file is empty. This is because the for loop initial with -1 and i change to int i = 0, it works fine now

Repeating UIAlert code over and over

I have this code:
-(IBAction)action2:(id)sender{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Confirm" message:#"If you press of a new group with the name you have set will be created" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles: #"Ok", nil];
[alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
if([title isEqualToString:#"Ok"])
{
NSString *destDir = [NSString stringWithFormat:#"/sandbox/%#/", namegroup.text];
NSString *filename5 = namegroup.text;
NSString *filename6 = #"group";
NSString *filename7 = #"groupdata";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *getImagePath5 = [documentsDirectory stringByAppendingPathComponent: [NSString stringWithFormat:#"%#", filename7]];
NSMutableArray *titles = [NSMutableArray array];
[titles addObject:filename5];
NSMutableArray *keys = [NSMutableArray array];
[keys addObject:filename6];
NSDictionary *dict = [NSDictionary dictionaryWithObjects:titles forKeys:keys];
NSString *jsonString = [dict JSONRepresentation];
NSData *jsonData = [jsonString dataUsingEncoding: NSUTF8StringEncoding];
[jsonData writeToFile: getImagePath5 atomically: YES];
[[self restClient] uploadFile:filename7 toPath:destDir
withParentRev:nil fromPath:getImagePath5];
}
}
If I press Ok button, the code is repeated over and over. how can I repeat it only 1 time??
I found out that there was another alert with the same cancel title, and when this was pressed it re-launched the same code. Thanks however for the help.