MFMailComposeViewController 在发送后丢失附件

MFMailComposeViewController losing attachments after sending

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

问题是,我随后发送了电子邮件,一旦收到,附件就消失了,取而代之的是名称为 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];
}

您发送了一个 mimeType:@"text/csv" 的附件。所以由于这个原因当你收到数据的时候。它将始终在文本 format.So 中更改您要发送的文件的格式。但是您发送的是整个文件以及 FILENAME 参数中的扩展名。所以你必须将文件名与扩展名分开。然后你发送它。

您需要更改一行代码..

// 使用NSData读取文件

NSData *fileData = [NSData dataWithContentsOfFile:file];

//至

NSData *fileData = [file dataUsingEncoding:NSUTF8StringEncoding];

// 也按照格式指定文件名..

// 添加附件

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

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

希望对您有所帮助...!

此代码为我正确附加了 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];