How do I send package-type documents as a mail attachment?
-
11-12-2019 - |
Question
I have a package-type document - i.e. it's really a folder, but it uses NSFileWrapper
and conforms to com.apple.package
to appear as a file - which I want to share by email. I've made an MFMailComposeViewController
and I'm trying to work out what to give to the first parameter of addAttachmentData:mimeType:fileName:
.
The package contains an image file and a plist, though that could change in the future.
How do I convert a package to data? Is that the right way of doing this?
Solution
As you said, a package is in reality a folder. It is interpreted as a package only on OSX operating systems.
As such, the mail protocol can't interpret it as a package / as a single file, and only sees a standard folder.
The only way to send this via email is to compress the files into a single file. You can do this by creating a ZIP archive of your package, or a tar.gz file for example.
There are multiple solutions to create a ZIP archive from code in Cocoa. You can use the libz library and C code directly, or use some third-party libraries (that already has generic code for it and helps you do this easier using Cocoa methods), like ZipArchive or others.
OTHER TIPS
My files are not large, so ZIP is overkill and I'm also trying to avoid using third party code. So I came up with a different approach to attach multiple files in a single e-Mail attachment.
First, I already have an NSFileWrapper object that contains all of the files I want in the attachment. The key is to use the NSFileWrapper's serializedRepresentation method to get an NSData object to use for the e-mail attachment. I'm using 'application/octet-stream' for the mimeType. When I get back around to opening the attachment, I use the NSFileWrapper's initWithSerializedRepresentation: method to get the original NSFileWrapper back.
This works for me because the attached file will only be used and opened by my App. Obviously, this won't work if you need to do something with the attachment outside of your App. In that case, ZIP seems like it would be the logical choice.