2012-11-07 32 views
0

發送郵件我想送郵件在我的應用程序的PHP文件作爲附件:通過iOS版

if ([MFMailComposeViewController canSendMail]) 
{ 
    MFMailComposeViewController *mailViewController = [[MFMailComposeViewController alloc] init]; 
    mailViewController.mailComposeDelegate = self; 
    [mailViewController setSubject:@""]; 
    [mailViewController setMessageBody:@"" isHTML:NO]; 
    mailViewController.navigationBar.tintColor = [UIColor blackColor]; 
    NSData *myData = [NSData dataWithContentsOfFile:[self getScriptPath]]; 
    NSString *fileName = @"upload.php"; 
    [mailViewController addAttachmentData:myData mimeType:@"text/html" fileName:fileName]; 
    [self presentViewController:mailViewController animated:YES completion:nil]; 
    [mailViewController release]; 
} 
else 
    NSLog(@"Device is unable to send email in its current state."); 

的郵件被髮送,但沒有附件......

+0

如果你登錄myData,它會說什麼? – sosborn

+0

MyData是0字節....嗯 – davidOhara

回答

3

我敢打賭你的[self getScriptPath]方法返回一個無效的路徑,或一個路徑到一個不存在的文件,因此[NSData dataWithContentsOfFile:...]可能會返回nil

您應該使用斷點或NSLog來檢查getScriptPath返回的值並相應地修復它。

例如,如果您在應用程序中嵌入了"upload.php"文件(您已將其添加到Xcode項目以及應用程序的其他資源中),則應該使用它來獲取腳本文件的有效路徑:

-(NSString*)getScriptPath 
{ 
    return [[NSBundle mainBundle] pathForResource:@"upload" ofType:@"php"]; 
} 

查看Bundle Programming Guide文檔以獲取更多信息。

+0

是的,我認爲是的......但我的方法返回正確的路徑!我的upload.php文件被拖入Xcode!那它在Documents目錄中?! – davidOhara

+1

否。如果您將'upload.php'文件拖放到Xcode中以將其包含在您的項目中,則該文件將包含在您的應用程序包中。 Documents目錄是您放置用戶在使用應用程序時即時創建的文件的位置;嵌入應用程序中的文件在編譯時位於應用程序包本身中。使用'[[NSBundle mainBundle] pathForResource:@「upload」ofType:@「php」]'來爲你的應用程序包中的''upload.php''資源文件獲取正確的路徑。 – AliSoftware

+0

Thx,就像一個魅力...... :) – davidOhara

0

使用此代碼附加圖像文件。

UIImage *emailImage = [UIImage imageNamed:@"loveCoding.png"]; 
[mailViewController addAttachmentData:UIImageJPEGRepresentation(emailImage, 1) mimeType:@"image/png" fileName:@"loveCocoa.png"]; 

要附加文件

NSString *fileName = [NSString stringWithFormat:@"Documents/%@.txt",sGame.userName]; 
    NSString *fullFilePath = [NSHomeDirectory() stringByAppendingPathComponent:fileName]; 

    NSString *emailFileName = [NSString stringWithFormat:@"%@_Report.txt",sGame.userName]; 

    NSData *myData = [NSData dataWithContentsOfFile:fullFilePath]; 

    [email addAttachmentData:myData mimeType:@"text/plain" fileName:emailFileName]; 
+0

這正是我所做的;) – davidOhara

+0

@chrizstone你需要指定fullPath – Guru

0

看起來像你的NSData沒有正確加載。從getScriptPath檢查你的路徑