【问题标题】:Adding multiple attachments to email using selection from UITableView使用 UITableView 中的选择向电子邮件添加多个附件
【发布时间】:2015-07-16 15:18:48
【问题描述】:

我想通过选择 UITableView 中列出的文件将在我的应用中创建的 csv 文件附加到电子邮件中。

我的 UITableView 中列出了所有文件,并且能够将单个选定的文件附加到电子邮件中而没有任何问题,但是在我的一生中,我无法弄清楚如何附加我在 UITableView 中选择的多个文件。

我将选定的文件存储在一个名为 selectedData 的 NSMutableArray 中。

我该怎么做呢?我一直在寻找答案一段时间,但没有发现与我正在尝试做的事情直接相关的东西。

到目前为止,这是我的代码:

- (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]];

        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]];

        NSLog(@"deselectedData %@",self.selectedData);
      }

}



#pragma mark - Email Selected Data

-(IBAction)emailButton:(id)sender
{


}

- (void)showEmail:(NSString*)file {

    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];

    // Determine the file name and extension
    NSArray *filepart = [file componentsSeparatedByString:@"."];
    NSString *filename = [filepart objectAtIndex:0];
    NSString *extension = [filepart objectAtIndex:1];

    // Get the resource path and read the file using NSData
    NSString *filePath = [[NSBundle mainBundle] pathForResource:filename ofType:extension];
    NSData *fileData = [NSData dataWithContentsOfFile:filePath];

    // Determine the MIME type
    NSString *mimeType;
    if ([extension isEqualToString:@"csv"]) {
        mimeType = @"text/csv";
    }

    // Add attachment
    [mc addAttachmentData:fileData mimeType:mimeType 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];
}

我们将不胜感激任何和所有的帮助。

【问题讨论】:

    标签: ios objective-c uitableview mfmailcomposeviewcontroller


    【解决方案1】:

    试试这样的。 假设所有文件都是相同的 mime 类型 csv。 并假设 self.selectedData 中的所有文件名都具有类似“myfile.csv”的结构。

    - (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 and extension
          NSArray *filepart = [file componentsSeparatedByString:@"."];
          NSString *filename = [filepart objectAtIndex:0];
          NSString *extension = [filepart objectAtIndex:1];
    
          // Get the resource path and read the file using NSData
          NSString *filePath = [[NSBundle mainBundle] pathForResource:filename ofType:extension];
          NSData *fileData = [NSData dataWithContentsOfFile:filePath];
    
          // Determine the MIME type
          NSString *mimeType;
          if ([extension isEqualToString:@"csv"]) {
              mimeType = @"text/csv";
          }
    
          // Add attachment
          [mc addAttachmentData:fileData mimeType:mimeType fileName:filename];
        }
    
        // Present mail view controller on screen
        [self presentViewController:mc animated:YES completion:NULL];
    
    }
    

    【讨论】:

    • 谢谢,我试试看,让你知道我的进展如何。
    • 我刚刚尝试了上面的方法,不幸的是它出错了,它不喜欢String,有没有可能是Swift?
    • 我将代码更改为以下内容:for (NSString *file in self.selectedData) 并运行了应用程序,这次它成功了,我从表格视图中选择了两个文件并添加了两个文件作为附件发送到电子邮件,但是附加的文件只是空白的 txt 文件,而不是我选择的 CSV。我已经编辑了原始问题以包含更多代码,以防我在那里出错。你能看看并建议我哪里出错了吗?
    • 感谢您的编辑。我确实在某个编辑器中“即时”编写了它,并且没有机会对其进行编译或错误检查。
    • 没问题,感谢您的帮助,非常感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 2019-05-05
    • 1970-01-01
    • 2023-03-21
    • 2011-02-03
    • 2020-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多