Friday, December 28, 2012

iOS Attaching a text file to email

Continuing my previous post about creating a text file iOS.
Refer to the post here.

Now that the file is created, you want to read the file and send it as an attachment.

NSString *fileName = @"yourfile.txt";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);

//your app directory will be always be the first one
NSString *directory = [paths objectAtIndex:0];
NSString *path = [directory stringByAppendingPathComponent:fileName];

//now get the data here.
//Not sure, if this is a good idea. Especially if the data is //huge
//better idea might be to open a file handle and read it line by //line
NSData *myData = [NSData dataWithContentsOfFile:path];

//email component
MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];

[mailer addAttachmentData:myData mimeType:@"text/plain",filename:fileName];


//that should be it.

No comments: