June
June

Reputation: 39

Attaching Email Automatically iOS

I have been building a survey app that users simply enter information in and its saved to a csv file. Im now at the stage where I need to attached the csv file within the app to an email address so when the user hits submit it sends the csv file in a email as an attachment automatically my code is as follows:

- (IBAction)send:(id)sender {

    NSString *savedFilePath = @"../contact.csv";
    NSData *csvData = [NSData dataWithContentsOfFile:savedFilePath];

    MFMailComposeViewController *mailcomposer = [[MFMailComposeViewController alloc] init];
    [mailcomposer setMailComposeDelegate:self];
    [mailcomposer addAttachmentData:csvData mimeType:@"text/csv" fileName:@"contact.csv"];
    [mailcomposer setToRecipients:@[@"[email protected]"]];
    [mailcomposer setSubject:self.subject.text];
    [mailcomposer setMessageBody:self.message.text isHTML:NO];
    [self presentModalViewController:mailcomposer animated:YES];
}

-(void) mailComposeController: (MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    [self dismissModalViewControllerAnimated:YES];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

This however doesnt attach the csv file... I have a feeling it may be to do with the line

 NSString *savedFilePath = @"../contact.csv";

However am not sure. If anyone can help please let me know... Im reaching breaking point with this one.

Upvotes: 2

Views: 78

Answers (1)

rckoenes
rckoenes

Reputation: 69499

The issue might be in the fact you are loading the NSData with a relative path.

NSString *savedFilePath = @"../contact.csv";
NSData *csvData = [NSData dataWithContentsOfFile:savedFilePath];

Try the create the full path to the file:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedFilePath = [documentsDirectory stringByAppendingPathComponent:@"result‌s.csv"];
NSData *csvData = [NSData dataWithContentsOfFile:savedFilePath];

Here I assume that the contact.csv is in the document directory.

Upvotes: 1

Related Questions