MFMailComposeViewController在发送后丢失附件

时间:2015-07-17 12:46:37

标签: ios objective-c xcode uitableview mfmailcomposeviewcontroller

我有一个头脑,我创建了一个UITableView来显示存储在文档目录中的记录数据,然后允许我选择多个文件并通过电子邮件发送它们。 这很好用,我选择要在我的电子邮件中发送的列出文件,单击电子邮件按钮,将显示一个附带文件列表的电子邮件。名称和扩展名是正确的。

问题是,我然后发送电子邮件,一旦收到附件,附件已消失,并被替换为名称为ATT00001.txt,ATT00002.txt等的txt文件。

任何人都可以向我解释为什么会发生这种情况以及如何解决这个问题?我在下面列出了我的代码:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return [filePathsArray count];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MainCell"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MainCell"];
    }

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSArray *fileList = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:nil];
    NSPredicate *fltr = [NSPredicate predicateWithFormat:@"self ENDSWITH '.csv'"];
    NSArray *csvFiles = [fileList filteredArrayUsingPredicate:fltr];
    NSLog(@"Contents of directory: %@", csvFiles);
    filePathsArray = [[NSFileManager defaultManager]contentsOfDirectoryAtPath:documentsDirectory error:nil];
    cell.textLabel.text = [csvFiles objectAtIndex:indexPath.row];

    return cell;
}

# pragma mark - Deleting data from Row.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    {
        NSString *fileName = [filePathsArray objectAtIndex:indexPath.row];
        NSString *path;
        NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        path = [paths objectAtIndex:0];
        path = [path stringByAppendingPathComponent:fileName];
        NSError *error;
        [filePathsArray removeObjectAtIndex:indexPath.row];

        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
        [tableView reloadData];
        if ([[NSFileManager defaultManager]fileExistsAtPath:path]) {
            if(![[NSFileManager defaultManager] removeItemAtPath:path error:&error])
            {
                NSLog(@"Delete file error:%@", error);
            }
            NSLog(@"Deleting file named: %@", path);
        }

    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (cell.accessoryType == UITableViewCellAccessoryNone) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        [self.selectedData addObject:[filePathsArray objectAtIndex:indexPath.row]];
        [[tableView indexPathsForSelectedRows] count];
        [self updateEmailButtonTitle];
        NSLog(@"selectedData %@",self.selectedData);

    }
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
        cell.accessoryType = UITableViewCellAccessoryNone;
        [self.selectedData removeObject:[filePathsArray objectAtIndex:indexPath.row]];
        [self updateEmailButtonTitle];
        NSLog(@"deselectedData %@",self.selectedData);
    }

}

#pragma mark - Email Selected Data

-(IBAction)emailButton:(id)sender
{
    [self showEmail];

}

- (void)showEmail {

    NSString *emailTitle = @"Your Data";
    NSString *messageBody = @"Attached is your recorded data.";

    MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
    mc.mailComposeDelegate = self;
    [mc setSubject:emailTitle];
    [mc setMessageBody:messageBody isHTML:NO];

    for (NSString *file in self.selectedData) {

        // Determine the file name
        NSString *filename = [self.selectedData objectAtIndex:0];

        // Read the file using NSData

        NSData *fileData = [NSData dataWithContentsOfFile:file];

        // Add attachment
        [mc addAttachmentData:fileData mimeType:@"text/csv" fileName:filename];
    }

    // Present mail view controller on screen
    [self presentViewController:mc animated:YES completion:NULL];

}

- (void) mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    switch (result)
    {
        case MFMailComposeResultCancelled:
            NSLog(@"Mail cancelled");
            break;
        case MFMailComposeResultSaved:
            NSLog(@"Mail saved");
            break;
        case MFMailComposeResultSent:
            NSLog(@"Mail sent");
            break;
        case MFMailComposeResultFailed:
            NSLog(@"Mail sent failure: %@", [error localizedDescription]);
            break;
        default:
            break;
    }

    // Close the Mail Interface
    [self dismissViewControllerAnimated:YES completion:NULL];
}

非常感谢任何和所有帮助。

编辑 - 这是已完成且正常工作的代码,感谢所有帮助过此的人:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    return [filePathsArray count];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MainCell"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MainCell"];
    }

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSArray *fileList = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:nil];
    NSPredicate *fltr = [NSPredicate predicateWithFormat:@"self ENDSWITH '.csv'"];
    NSArray *csvFiles = [fileList filteredArrayUsingPredicate:fltr];
    NSLog(@"Contents of directory: %@", csvFiles);
    filePathsArray = [[NSFileManager defaultManager]contentsOfDirectoryAtPath:documentsDirectory error:nil];
    cell.textLabel.text = [csvFiles objectAtIndex:indexPath.row];

    return cell;
}

# pragma mark - Deleting data from Row.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    {
        NSString *fileName = [filePathsArray objectAtIndex:indexPath.row];
        NSString *path;
        NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        path = [paths objectAtIndex:0];
        path = [path stringByAppendingPathComponent:fileName];
        NSError *error;
        [filePathsArray removeObjectAtIndex:indexPath.row];

        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
        [tableView reloadData];
        if ([[NSFileManager defaultManager]fileExistsAtPath:path]) {
            if(![[NSFileManager defaultManager] removeItemAtPath:path error:&error])
            {
                NSLog(@"Delete file error:%@", error);
            }
            NSLog(@"Deleting file named: %@", path);
        }

    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (cell.accessoryType == UITableViewCellAccessoryNone) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        [self.selectedData addObject:[filePathsArray objectAtIndex:indexPath.row]];
        [[tableView indexPathsForSelectedRows] count];
        [self updateEmailButtonTitle];
        NSLog(@"selectedData %@",self.selectedData);

    }
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
        cell.accessoryType = UITableViewCellAccessoryNone;
        [self.selectedData removeObject:[filePathsArray objectAtIndex:indexPath.row]];
        [self updateEmailButtonTitle];
        NSLog(@"deselectedData %@",self.selectedData);
    }

}


-(void)updateEmailButtonTitle
{

    NSArray *selectedRows = [self.tableView indexPathsForSelectedRows];


    if (selectedRows.count == self.selectedData.count)
    {
        self.emailButton.enabled = NO;
        self.emailButton.title = @"Email";

    } else if (selectedRows.count == 0) {
        self.emailButton.enabled = YES;
        self.emailButton.title = @"Email Selected Data";
    }
}

#pragma mark - Email Selected Data

-(IBAction)emailButton:(id)sender
{
    [self showEmail];

}

- (void)showEmail
{

    NSString *emailTitle = @"Your Data";
    NSString *messageBody = @"Attached is your recorded data.";

    MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
    mc.mailComposeDelegate = self;
    [mc setSubject:emailTitle];
    [mc setMessageBody:messageBody isHTML:NO];

    for (NSString *file in self.selectedData) {

        NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

        NSString *csvFilePath = [documentsDirectory stringByAppendingPathComponent:file]; // This will check the conents of the string "file" and match it with files located in the documents directory.
        NSData *myData = [NSData dataWithContentsOfFile:csvFilePath];

        NSLog(@"my nsdata is %@",myData);  //check whether your nsdata is nil or not

        [mc addAttachmentData:myData
                                     mimeType:@"text/csv"
                                     fileName:file];

        }

        [self presentViewController:mc animated:YES completion:nil];


    }



- (void) mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    switch (result)
    {
        case MFMailComposeResultCancelled:
            NSLog(@"Mail cancelled");
            break;
        case MFMailComposeResultSaved:
            NSLog(@"Mail saved");
            break;
        case MFMailComposeResultSent:
            NSLog(@"Mail sent");
            break;
        case MFMailComposeResultFailed:
            NSLog(@"Mail sent failure: %@", [error localizedDescription]);
            break;
        default:
            break;
    }

    // Close the Mail Interface
    [self dismissViewControllerAnimated:YES completion:NULL];
}

3 个答案:

答案 0 :(得分:3)

此代码为我正确附加了csv文件:

  NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

    NSString *csvFilePath = [documentsDirectory stringByAppendingPathComponent:file]; //This checkes the string "file" for a list of selected files which can then be matched up to the contents of the documents directory.
    NSData *myData = [NSData dataWithContentsOfFile:csvFilePath];

    NSLog(@"my nsdata is %@",myData);  //check whether your nsdata is nil or not

    [mc addAttachmentData:myData
                                 mimeType:@"text/csv"
                                 fileName:file];

答案 1 :(得分:1)

您需要更改一行代码..

//使用NSData

读取文件
NSData *fileData = [NSData dataWithContentsOfFile:file];

//为了

NSData *fileData = [file dataUsingEncoding:NSUTF8StringEncoding];

//还根据格式指定fileName ..

//添加附件

NSString* fileNameStr = [NSString stringWithFormat:@"%@.csv", filename];//fileName should be only name not entire path.

[mc addAttachmentData:fileData mimeType:@"text/csv" fileName:fileNameStr];

希望它可以帮助你......!

答案 2 :(得分:-1)

您已发送带有mimeType的附件:@“text / csv”。因此,当您收到数据时,由于这个原因。它将始终采用文本格式。因此,请更改要发送的文件的格式。但是您要将整个文件与文件一起发送到FILENAME参数中。所以你必须从extionsion中分离文件名。然后你发送它。