天道酬勤,学无止境

How can I convert my Zip-file to NSData to email my Zip file as an attachment

I', m using the Objective Zip library to compress several images i took. I came to the point (I guess) where I' zipping an image.

Now I'd like to send this zipped File with the mailcomposer. However I need to declare a "NSData object" within my mail function.

[picker addAttachmentData:"NSData object" mimeType:@"application/zip" fileName:@"test.zip"];

Here's a snippit of my code

-(IBAction)sendMail{
    NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0];

    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"test.zip"]; 
    NSArray *data = [[NSArray alloc] initWithObjects:@"first",@"second",@"third",nil];

    NSString *docDir3 = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *pngFilePath4 = [NSString stringWithFormat:@"%@/foto2.jpg",paths];
    [data writeToFile:pngFilePath4 atomically:YES];

    NSData * fotoData = [[NSData alloc] initWithContentsOfFile:pngFilePath4];

    NSFileManager *manager = [[NSFileManager alloc] init]; 
    [manager removeItemAtPath:pngFilePath4 error:nil];

    ZipFile *readFile = [[ZipFile alloc] initWithFileName:path mode:ZipFileModeCreate];

    ZipWriteStream *stream = [readFile writeFileInZipWithName:@"foto2.jpg" compressionLevel:ZipCompressionLevelNone];

    [stream writeData:fotoData];
    [stream finishedWriting];

    MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
    picker.mailComposeDelegate=self;

    [picker addAttachmentData:"NSData Object" mimeType:@"application/zip" fileName:@"test.zip"];

    Class mailclass = (NSClassFromString(@"MFMailComposeViewController"));
    if([mailclass canSendMail]){
        [self presentModalViewController:picker animated:YES];
    }

    [readFile close];
    [data2 release];
    [fotoData release];
}

I think i need to make another NSData object from the readFile object and place this within the [picker attachmentData: method]. Hope someone can point me in the right direction.

EDIT

Still can't get this to work properly. It takes realy long to send the zip file (Even through wifi). When I open the zip image I get an error which says that the file cannot be opened. Here's my code:

NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0];

    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"test.zip"]; 
    NSArray *data = [[NSArray alloc] initWithObjects:@"first",@"second", nil];

    NSString *docDir3 = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 
    NSString *pngFilePath3 = [NSString stringWithFormat:@"%@/foto2.jpeg",docDir3];
    NSData * imageData2 = [[[NSData alloc] initWithContentsOfFile:pngFilePath3] autorelease];

    [data writeToFile:pngFilePath3 atomically:YES];

    ZipFile *readFile = [[ZipFile alloc] initWithFileName:path mode:ZipFileModeCreate];

    ZipWriteStream *stream = [readFile writeFileInZipWithName:@"foto2.jpeg" compressionLevel:ZipCompressionLevelNone];

    [stream writeData:imageData2];
    [stream finishedWriting];


    MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
    picker.mailComposeDelegate=self;
   [picker addAttachmentData:[NSData dataWithContentsOfFile:path] mimeType:@"application/zip" fileName:@"test.zip"];

    Class mailclass = (NSClassFromString(@"MFMailComposeViewController"));
    if([mailclass canSendMail]){
        [self presentModalViewController:picker animated:YES];
    }

    [data release];
    [readFile close];

Thanks in advance for helping me out!

评论

The ZipWriteStream is writing to path, and getting data from a file path is done using [NSData dataWithContentsOfFile:path].

[picker addAttachmentData:[NSData dataWithContentsOfFile:path] 
                 mimeType:@"application/zip" 
                 fileName:@"test.zip"];

Objective-Zip does throw exceptions when a write failure occurs so make sure you add a try/catch around the write operation and make sure your data is not nil.

受限制的 HTML

  • 允许的HTML标签:<a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • 自动断行和分段。
  • 网页和电子邮件地址自动转换为链接。

相关推荐
  • 将 .zip 文件转换为 NSData(convert .zip file into NSData)
    问题 嘿,用 zip 文件初始化 NSData 是否正确? 我想将一个 zip 文件转换为 NSData 并用数据构建另一个文件(用简单的语言“复制它”)。 我的代码如下: NSURL *theFileUrl = [NSURL URLWithString: @"file://localhost/Users/xxx/Desktop/testZippedFile.zip"]; NSData *data = [NSData dataWithContentsOfURL: theFileUrl]; 当我NSLog(@"Data: %@", data) ,我确实得到了一些输出,但是当我尝试用这些数据初始化 NSString 时,它不起作用: NSString *str = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]; `NSLog(@"String: %@", string)` 我得到的日志为: String: PK 谁能指出我的错误。 提前致谢! 回答1 为什么要这样做? NSFileManager 会为你做的 :) [[NSFileManager defaultManager] copyItemAtPath:oldPath toPath:newPath error:nil]; 但是
  • 使用 play 2.5 流式传输即时创建的 zip 并使用背压流式传输 akka 流(stream a zip created on the fly with play 2.5 and akka stream with backpressure)
    问题 我想使用带有背压的 akka 流通过 play-framework 2.5 流式传输动态创建的 zip(而不将其完全放入内存中)。 这是我的代码,带有一个即时创建的小 zip(16KB)。当客户端下载与操作关联的 url 时,下载不会开始。 import java.util.zip.{ ZipEntry, ZipOutputStream, GZIPOutputStream } import akka.stream.scaladsl._ import akka.util.ByteString import play.api.mvc._ import scala.concurrent.duration._ import java.io.{ BufferedOutputStream, ByteArrayOutputStream } import scala.concurrent.{ Promise, Future } import akka.stream.OverflowStrategy class ZipController extends Controller { def getStreamedZip = Action { val source: Source[ByteString, java.io.OutputStream] = StreamConverters
  • 将带有图像的 NSAttributedString 保存到 RTF 文件时遇到问题(trouble saving NSAttributedString, with image, to an RTF file)
    问题 我有一些输出,它是一个非常简单的 RTF 文件。 当我生成此文档时,用户可以通过电子邮件发送它。 所有这些工作正常。 该文件看起来不错。 获得 NSAttributedString 后,我创建一个 NSData 块,并将其写入文件,如下所示: NSData* rtfData = [attrString dataFromRange:NSMakeRange(0, [attrString length]) documentAttributes:@{NSDocumentTypeDocumentAttribute: NSRTFTextDocumentType} error:&error]; 该文件可以通过电子邮件发送。 当我检查电子邮件时,一切都很好。 现在,我的任务是在文档顶部添加一个 UIImage。 太好了,所以我正在创建一个这样的属性字符串: NSTextAttachment *attachment = [[NSTextAttachment alloc] init]; UIImage* image = [UIImage imageNamed:@"logo"]; attachment.image = image; attachment.bounds = CGRectMake(0.0f, 0.0f, image.size.width, image.size.height)
  • Zipfile download through CURL to an actual Zip-file in your file structure
    I am trying to build a file downloader with the RubyGem Curb. (Look at This Question.) I am trying to download a zip file and then with the class File I am trying to actually make the file so that I can double click it in Finder (I am on OS X). How would I go about to convert this "Curl'ed" body to a zip-file. require 'rubygems' require 'curb' class Download def start curl = Curl::Easy.new('http://wordpress.org/latest.zip') curl.perform curl.on_body { |d| f = File.new('test.zip', 'w') {|f| f.write d} } end end dl = Download.new dl.start I am not getting any error, neither can I find any file
  • 带有电子邮件正文的 NSMutableArray 数据附件?(NSMutableArray Data Attachement With E-mail Body?)
    问题 我的 NSMutableArray 数据采用 NSData 格式。我试图将 NSMutableArray 数据附加到电子邮件正文。这是我的 NSMutableArray 代码: NSUserDefaults *defaults1 = [NSUserDefaults standardUserDefaults]; NSString *msg1 = [defaults1 objectForKey:@"key5"]; NSData *colorData = [defaults1 objectForKey:@"key6"]; UIColor *color = [NSKeyedUnarchiver unarchiveObjectWithData:colorData]; NSData *colorData1 = [defaults1 objectForKey:@"key7"]; UIColor *color1 = [NSKeyedUnarchiver unarchiveObjectWithData:colorData1]; NSData *colorData2 = [defaults1 objectForKey:@"key8"]; UIFont *color2 = [NSKeyedUnarchiver unarchiveObjectWithData:colorData2]; CGFloat
  • 从 iCloud 文档选取器附加 iWork 文档不起作用,因为它们是目录而不是文件(Attaching iWork documents from iCloud Document Picker does not work because they are directories not files)
    问题 将任何 iWork 文档( Pages 、 Keynote 、 Numbers )从UIDocumentPickerViewController转换为NSData似乎不起作用,因为它们不是文件而是目录。 这是我的代码: NSString *fileName = [[url path] lastPathComponent]; NSData *fileData = [[NSFileManager defaultManager] contentsAtPath:[docPickerUrl path]]; NSString *fileExtension = [docPickerUrl pathExtension]; NSString *UTI = (__bridge_transfer NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)fileExtension, NULL); NSString *contentType = (__bridge_transfer NSString *)UTTypeCopyPreferredTagWithClass((__bridge CFStringRef)UTI, kUTTagClassMIMEType
  • 使用php将多个文件下载为zip文件(Download multiple files as a zip-file using php)
    问题 如何使用php下载多个文件作为zip文件? 回答1 您可以使用ZipArchive类创建一个ZIP文件并将其流式传输到客户端。 就像是: $files = array('readme.txt', 'test.html', 'image.gif'); $zipname = 'file.zip'; $zip = new ZipArchive; $zip->open($zipname, ZipArchive::CREATE); foreach ($files as $file) { $zip->addFile($file); } $zip->close(); 并流式传输: header('Content-Type: application/zip'); header('Content-disposition: attachment; filename='.$zipname); header('Content-Length: ' . filesize($zipname)); readfile($zipname); 第二行强制浏览器向用户显示一个下载框,并提示名称filename.zip。 第三行是可选的,但是某些(主要是较旧的)浏览器在某些情况下会出现问题,而未指定内容大小。 回答2 这是在PHP中制作ZIP的一个有效示例: $zip = new ZipArchive(); $zip
  • Create CSV file in Swift and write to file
    I have an app I've made that has a UITableView with todoItems as an array for it. It works flawlessly and I have an export button that creates a CSV file from the UITableView data and emails it out: // Variables var toDoItems:[String] = [] var convertMutable: NSMutableString! var incomingString: String = "" var datastring: NSString! // Mail alert if user does not have email setup on device func showSendMailErrorAlert() { let sendMailErrorAlert = UIAlertView(title: "Could Not Send Email", message: "Your device could not send e-mail. Please check e-mail configuration and try again.", delegate
  • 如何在MFMailComposeViewController的MailComposer工作表中添加UIImage(How to add a UIImage in MailComposer Sheet of MFMailComposeViewController)
    问题 我想在MFMailComposerViewController的撰写表中插入UIImage 。 请注意,我不想附加它们,但是我想使用HTML代码将它们放在表格中,这将成为电子邮件正文的一部分。 回答1 再次返回新答案。 不过,我仍然保留以前的代码,因为我仍然不相信没有办法使用它。 我会自己坚持下去。 以下代码可以正常工作。 穆斯塔法(Mustafa)建议对图像进行base64编码,并说它们仅适用于Apple到Apple,但实际上并非如此。 Base64编码现在可以在大多数邮件客户端上使用(IE以前不支持它,但是现在支持特定大小的图像,尽管我不确定大小是多少)。 问题是,像Gmail这样的邮件客户端会剥夺您的图像数据,但是有一个简单的解决方法...只需将<b> and </b>标记放在<img ...>标记周围就可以了。尽力防止它被剥夺。 为了使图像进入您的电子邮件,您需要使base64编码器进入您的项目。 那里有几个(虽然大多数是C),但是我发现的最简单的ObjC被Matt Gallagher称为NSData + Base64 (复制后我从名称中删除了“ +”,因为它给我带来了问题)。 将.h和.m文件复制到您的项目中,并确保在计划使用该文件的位置#import .h文件。 然后像这样的代码会将图像放入您的电子邮件正文中... - (void)createEmail { /
  • 如何使用 AWS CLI 创建 AWS Lambda 函数?(How can I create an AWS Lambda function using the AWS CLI?)
    问题 我正在尝试使用以下命令创建 AWS Lambda 函数 aws lambda create-function \ --function-name foo\ --runtime nodejs\ --role lambda_basic_execution \ --handler asdf --zip-file "fileb:://boom.zip" 我在目录中有一个名为 boom.zip 的文件。 但我无法使用上述命令进行部署。 我得到的失败信息是 --zip-file 必须是带有 fileb:// 前缀的文件。 有没有人有使用 AWS CLI 创建 lambda 函数的工作示例? 回答1 您在文件规范中有一个额外的冒号 ':'。 $ aws lambda create-function --function-name foo --runtime nodejs --role lambda_basic_execution --handler asdf --zip-file "fileb:://boom.zip" --zip-file must be a file with the fileb:// prefix. Example usage: --zip-file fileb://path/to/file.zip $ aws lambda create-function -
  • Android Studio Gradle 读取 ZIP 文件时出错(Android Studio Gradle Error Reading ZIP-File)
    问题 我的 Android Studio (0.8.9) 出现了一些问题。 当我想创建一个新项目、调试它或其他什么时,只会出现如下错误消息: Gradle 'Afsddsf' project refresh failed Error:Cause: error reading zip file 在顶部显示: gradle project sync failed. basic functionality will not work properly 我的 .gradle 文件中已经有了 zip 文件夹。 我在 google 中发现了很多关于打开 zip 文件的错误。 但没有一个符合我的错误。 我还安装了所有的 SDK 等等。 也试过在这个项目中设置gradlesettings,选择了本地的gradle,也没有成功。 也许这有助于说,我的“handyvieweremulator”(通常显示在程序右侧的开头)也不起作用。 他有一些参考问题。 我今晚要发布我的错误日志,如果这也有帮助的话。 谢谢你的帮助 ... 回答1 我遇到了同样的问题,这是它的解决方法:(在 OSX 10.10.5 下的 Android Studio 上测试) 首选项 --> 构建、执行、部署 --> 构建工具 --> Gradle 然后检查离线工作。 这将使用您的本地 gradle 发行版,并在您同步 Gradle
  • Creating a vCard in iPhone
    I'm trying to create a vCard representation in the iPhone. I created a string representation for the vCard. I'm not sure how to convert it into the NSData form in order to mail it as an attachment. This is what I have so far: NSString *vCardString = [vCard getVCFString]; // returns string representation for vCard NSData *vCardData = [vCardString dataUsingEncoding:NSUTF8StringEncoding]; [mailController addAttachmentData:vCardData mimeType:@"text/x-vcard" fileName:@"LocationInfo"]; When I click on the attachment when I do a test email, it goes to the create new contact/add as existing contact
  • 更新的文档未在 Gmail 中附加为 PDF(Updated doc not attaching as PDF in Gmail)
    问题 我正在使用 Google Apps Script 创建 doc 文件的副本并将电子表格中的数据保存到新文件中,然后将其作为 PDF 附件发送到电子邮件。 一切正常,除了 pdf 文件显示的是来自源文件的默认值而不是更新的值。 这是我的代码, var lr = dataSheet.getLastRow(); var dataRange = dataSheet.getRange(lr, 1, 1, 3).getValues(); var firstName = dataRange[0][1]; var lastName = dataRange[0][2]; var email = dataRange[0][3]; var emailText = "Hi "+firstName+",\n\nThank you for signing up."; var emailSubject = "Test PDF"; var fileTemplate = DriveApp.getFileById("FILE_ID"); // Get Template File Id var fileCopied = fileTemplate.makeCopy("Doc Copy-"+new Date()).getId(); // Make a copy of the template and get the
  • convert UIImage to NSData
    I am using this code in my app which will help me to send a image. However, I have an image view with an image. I have no file in appbundle but have the image in my side. How can I change the below code ? Can anyone tell me how can I convert myimage to NSData ? // Attach an image to the email NSString *path = [[NSBundle mainBundle] pathForResource:@"rainy" ofType:@"jpg"]; NSData *myData = [NSData dataWithContentsOfFile:path]; [picker addAttachmentData:myData mimeType:@"image/jpeg" fileName:@"rainy"];
  • How to increase the maximum size of the AWS lambda deployment package (RequestEntityTooLargeException)?
    I upload my lambda function sources from AWS codebuild. My Python script uses NLTK so it needs a lot of data. My .zip package is too big and an RequestEntityTooLargeException occurs. I want to know how to increase the size of the deployment package sent via the UpdateFunctionCode command. I use AWS CodeBuild to transform the source from a GitHub repository to AWS Lambda. Here is the associated buildspec file: version: 0.2 phases: install: commands: - echo "install step" - apt-get update - apt-get install zip -y - apt-get install python3-pip -y - pip install --upgrade pip - pip install -
  • 如何将 NSMutableArray 转换为 NSString?(How can I convert NSMutableArray into NSString?)
    问题 我正在尝试将(或复制?) NSMutableArray转换为NSString 。 我想我的问题是我不太了解NSString的结构。 转换后我想将其附加在电子邮件正文中。 这是我的代码: - (IBAction)sendEmail { NSLog(@"sendEmail"); [textView resignFirstResponder]; [textView1 resignFirstResponder]; if ([MFMailComposeViewController canSendMail]) { // set the sendTo address NSMutableArray *recipients = [[NSMutableArray alloc] initWithCapacity:1]; [recipients addObject:@"example@yahoo.com"]; MFMailComposeViewController *controller = [[MFMailComposeViewController alloc] init]; controller.mailComposeDelegate = self; [controller setSubject:@"Iphone Game"]; NSString *string = [string
  • Android Studio Gradle Error Reading ZIP-File
    I got some problems with my Android Studio (0.8.9). When i want to create a new project, debug it or whatever, there just appears a error message like: Gradle 'Afsddsf' project refresh failed Error:Cause: error reading zip file in the top it shows: gradle project sync failed. basic functionality will not work properly I already have the zip-Folder in my .gradle-File. I found a lot of errors here in google about opening the zip-file. but noone of these matched to my error. I also installed all of the SDK's and so on. Also tried to set up the gradlesettings in this project and choosed the local
  • 在 Swift 中创建 CSV 文件并写入文件(Create CSV file in Swift and write to file)
    问题 我有一个应用程序,它有一个UITableView和todoItems作为它的array 。 它完美无缺,我有一个导出按钮,可以从UITableView数据创建一个 CSV 文件并将其通过电子邮件发送出去: // Variables var toDoItems:[String] = [] var convertMutable: NSMutableString! var incomingString: String = "" var datastring: NSString! // Mail alert if user does not have email setup on device func showSendMailErrorAlert() { let sendMailErrorAlert = UIAlertView(title: "Could Not Send Email", message: "Your device could not send e-mail. Please check e-mail configuration and try again.", delegate: self, cancelButtonTitle: "OK") sendMailErrorAlert.show() } // MARK
  • 我的批处理文件中只运行第一个 lambda 更新语句(Only first lambda update statement is running in my batch file)
    问题 环境: 视窗 10 命令提示符 为什么我的批处理文件中只运行第一个 lambda 更新? 这是一个异步问题吗? 脚本文件 ... aws lambda update-function-code --function-name "fx1" --zip-file fileb://zip1.zip aws lambda update-function-code --function-name "fx2" --zip-file fileb://zip2.zip 回答1 假设, aws是一个批处理文件: 当您从批处理文件 (A) 执行另一个批处理文件 (B) 时,您将控制权从 (A) 转移到 (B),如果 (B) 结束,则不会“返回”到 (A)。 当您调用批处理文件 (B) 时,(A) 将暂停,直到 (B) 完成; 控制返回给 (A) 并且 (A) 继续下一行。 所以你不应该执行aws: aws lambda update-function-code --function-name "fx1" --zip-file fileb://zip1.zip 但称之为: call aws lambda update-function-code --function-name "fx1" --zip-file fileb://zip1.zip
  • 附加到电子邮件的文件 - 我正在尝试打开 myapp(File attached to Email - I am trying to open myapp)
    问题 我找到了几篇文章,并在我的 info.plist 中添加了 3 个部分。 当我运行我的应用程序时,电子邮件有一个带有“ntdb”后缀的附加文件,但电子邮件似乎无法识别扩展名。 我假设我一定在 plist 中输入了错误,但是在过去 2 天尝试了每种组合后,我不知道还有什么要改变的。 谁能告诉我我做错了什么? 电子邮件中的文件名是日期和 ntdb,如:“myfile 09-06-2011.ntdb” <key>CFBundleDocumentTypes</key> <array> <dict> <key>CFBundleTypeIconFiles</key> <array> <string>icon57</string> </array> <key>CFBundleTypeName</key> <string>myAppName</string> <key>CFBundleTypeRole</key> <string>Viewer</string> <key>LSHandlerRank</key> <string>Owner</string> <key>LSItemContentTypes</key> <array> <string>com.myCompanyName.myAppName.ntdb</string> </array> </dict> </array> <key