You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Objective C在Gmail中添加PDF附件失败问题求助

解决Gmail应用无法加载PDF附件的问题

你当前的代码存在两个核心问题,导致Gmail无法识别附件:

  1. Base64字符串未做URL编码,其中的+、/、=等特殊字符会破坏URL结构,导致参数被截断
  2. Gmail的attachment参数需要指定文件名、MIME类型、编码数据的完整格式,而非单纯的Base64字符串

修正后的代码

NSString *pdfPath = [[NSBundle mainBundle] pathForResource:@"MyFile" ofType:@"pdf"];
NSData *pdfData = [NSData dataWithContentsOfFile:pdfPath];
NSString *pdfBase64 = [pdfData base64EncodedStringWithOptions:0];

// 对Base64字符串做URL编码,避免特殊字符干扰
NSString *encodedBase64 = [pdfBase64 stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

// 构造符合Gmail要求的attachment参数:文件名:MIME类型:编码后的数据
NSString *attachmentParam = [NSString stringWithFormat:@"MyFile.pdf:application/pdf:%@", encodedBase64];

NSString *gmailScheme = [NSString stringWithFormat:@"googlegmail:///co?to=&subject=&body=&attachment=%@", attachmentParam];
NSURL *gmailURL = [NSURL URLWithString:gmailScheme];

if ([[UIApplication sharedApplication] canOpenURL:gmailURL]) {
    [[UIApplication sharedApplication] openURL:gmailURL options:@{} completionHandler:nil];
}

额外验证点

  • 打印pdfPath确认文件路径是否正确,确保PDF文件已正确加入项目主Bundle
  • 若附件过大,Base64编码后可能超出URL长度限制,这种情况建议改用文档交互控制器(UIDocumentInteractionController)分享文件

内容的提问来源于stack exchange,提问作者Yadukrishnan A

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 19:24:52