【问题标题】:MFMailComposeViewController losing attachments after sending发送后 MFMailComposeViewController 丢失附件
【发布时间】:2015-07-17 12:46:37
【问题描述】:

我有一个挠头,我创建了一个 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];
}

【问题讨论】:

  • ATT00001.txt 是否包含任何数据? txt 文档中的数据与您保存时一样正确吗?
  • @Vidhyan 不幸的是,它们是空白文件。
  • 简单。 csv 文件未附加到您的电子邮件中。您可以看到 csv 文件附加到电子邮件的图标,但实际上没有 csv 文件附加到电子邮件。
  • 发布您的nsdata并检查路径中是否存在csv文件
  • 您的电子邮件附件代码有问题

标签: ios objective-c xcode uitableview mfmailcomposeviewcontroller


【解决方案1】:

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

【讨论】:

  • 谢谢,我会试一试,让您知道我的进展情况。感谢您在这方面的帮助。
  • 谢谢,这几乎可以工作,但不太正确,我已经编辑了您的答案以显示完成的工作答案。
【解决方案2】:

你需要改一行代码..

// 使用 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];

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

【讨论】:

  • 嗨@Vidhyanand,谢谢你的上述,它确实解决了附件问题但是它揭示了另一个问题,附件不包含存储在我选择的文档目录中的数据,而是创建了一个CSV 文件的第一个字段中包含文件目录中文件的名称。你能从代码中看出我哪里出错了吗?
【解决方案3】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-24
    • 2013-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多