iPhone:收件人无法使用电子邮件附件

时间:2013-10-05 09:56:37

标签: objective-c file csv email-attachments

我正在尝试发送文件,但是当我打开收到的电子邮件时,附件已消失,好吧,只有一个,因为图像在那里。 文件格式为text / plain,扩展名为.csv。在模拟器上工作,我可以打开并阅读文件,完全没有问题。一旦将应用程序安装在iPhone(iOS 7)或iPad(iOS 6.1)上,该文件就会附加到电子邮件中,但正如我之前所说,该文件会在到达收件人之前消失。 iPhone屏幕截图: iphone Screen Capture

当我在电脑上打开电子邮件时: Mail screen capture

我用来编写和加载文件的代码:

- (IBAction)buttonSendData:(id)sender {

    if ([self checkUIPicker])

    {
        //fetching data

        COAppDelegate *appDelegate = (COAppDelegate *)  [[UIApplication sharedApplication]delegate];
        NSManagedObjectContext *context = [appDelegate managedObjectContext];
        NSError *error;

        NSEntityDescription *entity = [NSEntityDescription entityForName:@"Tiempos" inManagedObjectContext:context];
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc ]init];

        [fetchRequest setEntity:entity];

        NSPredicate *sectionAndControl = [NSPredicate predicateWithFormat:@"(tramo == %@) AND (control == %@)", section, control];
        [fetchRequest setPredicate:sectionAndControl];

        NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]initWithKey:@"dorsal" ascending:YES];
        [fetchRequest setSortDescriptors:@[sortDescriptor ]];

        dorsalesPorTramoYcontrol = [context executeFetchRequest:fetchRequest error:&error];

        if (!dorsalesPorTramoYcontrol || !dorsalesPorTramoYcontrol.count) {
            UIAlertView *alertFail = [[UIAlertView alloc]initWithTitle:@"Atención" message:@"No hay registros que cumplan esos criterios" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
            [alertFail show];

        }
    }
        if (dorsalesPorTramoYcontrol && dorsalesPorTramoYcontrol.count )
            {
                NSMutableString *mainString = [[ NSMutableString alloc]initWithString:@"dorsal,paso,tiempo\n"];

                for (NSManagedObject *get in dorsalesPorTramoYcontrol) {

                     //dorsales
                    NSString *string =[get valueForKey:@"dorsal"];
                    [mainString appendFormat:@"%@,",string];

                    //paso
                    string = [get valueForKey:@"paso"];
                    string=[string stringByReplacingOccurrencesOfString:@"\"" withString:@"\"\""];
                    [mainString appendFormat:@"%@,",string];


                    //tiempo
                    string = [get valueForKey:@"tiempo"];
                    string=[string stringByReplacingOccurrencesOfString:@"\"" withString:@"\"\""];
                    [mainString appendFormat:@"%@",string];

                    //new line
                    [mainString appendFormat:@"\n"];


             }

                NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
                NSString *documentsDirectoryPath = [paths objectAtIndex:0];
                file = [documentsDirectoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"/Tramo#%@_Control#%@.csv",section,control]];

                NSData *settingsData;
                settingsData = [mainString dataUsingEncoding:NSASCIIStringEncoding];

                if ([settingsData writeToFile:file atomically:YES]) {
                    NSLog(@"writing Ok");

                    [self composeEmail];
                    }
            }

}

-(void)composeEmail{

    if ([MFMailComposeViewController canSendMail])
    {

        MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];
        mailer.mailComposeDelegate = self;
        [mailer setSubject:[NSString   stringWithFormat:@"Resultados Tramo: %@ - Control: %@", section, control]];
        NSArray *toRecipients = [NSArray arrayWithObjects:@"turkish@mundo-r.com", nil];
        [mailer setToRecipients:toRecipients];

        //Clasicos Ourense Logo
        UIImage *myImage = [UIImage imageNamed:@"clasicosOurense.png"];
        NSData *imageData = UIImagePNGRepresentation(myImage);
        [mailer addAttachmentData:imageData mimeType:@"image/png" fileName:@"Icon"];

        //file attachment
        // 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];

        // Add attachment
        [mailer addAttachmentData:fileData mimeType:@"text/plain" fileName:filename];

        NSString *emailBody =
        [NSString   stringWithFormat:@"Resultados Tramo: %@ - Control: %@ \nDorsal - Paso - Tiempo", section, control];
        [mailer setMessageBody:emailBody isHTML:NO];
        mailer.modalPresentationStyle = UIModalPresentationPageSheet;
        [self presentViewController:mailer animated:YES completion:nil];
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Failure"
                                                        message:@"Your device doesn't support the composer sheet"
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles: nil];
        [alert show];
    }
}



-(BOOL) checkUIPicker{

    if ((control.length == 0) || (section.length == 0))
    {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Atención" message:@"Escoge un tramo y un control horario" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [alert show];
        return NO;

    }else if ((!control.length==0) && (!section.length==0 ))   {
        UIAlertView *alertSend = [[UIAlertView alloc]initWithTitle:@"Atención" message:[NSString stringWithFormat:@"Vas a enviar la información correspondiente al control: %@ del tramo: %@", control, section] delegate:self cancelButtonTitle:@"Correcto" otherButtonTitles: nil];
        [alertSend show];
        return YES;
    }

    return NO;
}

- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{
    switch (result)
    {
        case MFMailComposeResultCancelled:
            NSLog(@"Mail cancelled: you cancelled the operation and no email message was queued.");
            break;
        case MFMailComposeResultSaved:
            NSLog(@"Mail saved: you saved the email message in the drafts folder.");
            break;
        case MFMailComposeResultSent:
            NSLog(@"Mail send: the email message is queued in the outbox. It is ready to send.");
            break;
        case MFMailComposeResultFailed:
            NSLog(@"Mail failed: the email message was not saved or queued, possibly due to an error.");
            break;
        default:
            NSLog(@"Mail not sent.");
            break;
    }
    // Remove the mail view
    [self dismissViewControllerAnimated:YES completion:nil];
}

失败在哪里? 谢谢!

1 个答案:

答案 0 :(得分:0)

NSDatanull

更简单的事情更好。使用提供的代码here来附加csv文件,它现在可以正常工作。

替换为

//file attachment
// 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];

// Add attachment
[mailer addAttachmentData:fileData mimeType:@"text/plain" 
                                   fileName:filename];

由:

[mailer addAttachmentData:[NSData dataWithContentsOfFile:file] mimeType:@"text/csv" 
                                                               fileName:file];