Im trying to zip up my sqlite files from my documents directory to send via mail using https://github.com/mattconnolly/ZipArchive.
NSString *filePath = [[NSHomeDirectory() stringByAppendingPathComponent:#"Documents"] stringByAppendingPathComponent:#"app.sqlite"];
NSString *filePath2 = [[NSHomeDirectory() stringByAppendingPathComponent:#"Documents"] stringByAppendingPathComponent:#"app.sqlite-shm"];
NSString *filePath3 = [[NSHomeDirectory() stringByAppendingPathComponent:#"Documents"] stringByAppendingPathComponent:#"app.sqlite-wal"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *archivePath = [documentsDirectory stringByAppendingString:#".zip"];
//Zip up files
ZipArchive *archiver = [[ZipArchive alloc] init];
[archiver CreateZipFile2:archivePath];
[archiver addFileToZip:filePath newname:#"backUp.sqlite"];
[archiver addFileToZip:filePath2 newname:#"backUp.sqlite-shm"];
[archiver addFileToZip:filePath3 newname:#"backUp.sqlite-wal"];
MFMailComposeViewController *mailView = [[MFMailComposeViewController alloc] init];
if (mailView != nil) {
mailView.mailComposeDelegate = self;
[mailView setSubject:#"Database"];
//Attach zip file
[mailView addAttachmentData:[NSData dataWithContentsOfFile:archivePath] mimeType:#"application/zip" fileName:#"test.zip"];
[mailView setMessageBody:#"Database attached" isHTML:NO];
[self presentViewController:mailView animated:YES completion: NULL];
}
The attachment appears in the email preview on the device but when it arrives with the recipient the attachment has vanished?
also tried this:
NSString *filePath = [[NSHomeDirectory() stringByAppendingPathComponent:#"Documents"] stringByAppendingPathComponent:#"app.sqlite"];
NSString *filePath2 = [[NSHomeDirectory() stringByAppendingPathComponent:#"Documents"] stringByAppendingPathComponent:#"app.sqlite-shm"];
NSString *filePath3 = [[NSHomeDirectory() stringByAppendingPathComponent:#"Documents"] stringByAppendingPathComponent:#"app.sqlite-wal"];
DebugLog(#"DB path is: %#", filePath);
NSError *error = nil;
NSData *fileData = [[NSData alloc] initWithContentsOfFile:filePath options:0UL error:&error];
NSString* fileDataString = [[NSString alloc] initWithData:fileData encoding:NSNonLossyASCIIStringEncoding];
NSData *fileData2 = [[NSData alloc] initWithContentsOfFile:filePath2 options:0UL error:&error];
NSString* fileData2String = [[NSString alloc] initWithData:fileData2 encoding:NSNonLossyASCIIStringEncoding];
NSData *fileData3 = [[NSData alloc] initWithContentsOfFile:filePath3 options:0UL error:&error];
NSString* fileData3String = [[NSString alloc] initWithData:fileData3 encoding:NSNonLossyASCIIStringEncoding];
if (error != nil) {
DebugLog(#"Failed to read the file: %#", [error localizedDescription]);
} else {
if (fileData == nil) {
DebugLog(#"File data is nil");
}
}
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *archivePath = [documentsDirectory stringByAppendingString:#".zip"];
//Zip up documents directory
ZipArchive *archiver = [[ZipArchive alloc] init];
[archiver CreateZipFile2:archivePath];
[archiver addFileToZip:fileDataString newname:#"backUp.sqlite"];
[archiver addFileToZip:fileData2String newname:#"backUp.sqlite-shm"];
[archiver addFileToZip:fileData3String newname:#"backUp.sqlite-wal"];
MFMailComposeViewController *mailView = [[MFMailComposeViewController alloc] init];
if (mailView != nil) {
mailView.mailComposeDelegate = self;
[mailView setSubject:#"Database"];
//Attach zip file
[mailView addAttachmentData:[NSData dataWithContentsOfFile:archivePath] mimeType:#"application/zip" fileName:#"test.zip"];
[mailView setMessageBody:#"Database attached" isHTML:NO];
[self presentViewController:mailView animated:YES completion: NULL];
}
same behaviour zip file does not arrive with email
Logging the archivePath gives me /var/mobile/Containers/Data/Application/1D32A3AA-A431-46234-AE4B-ED944CA2D883F4/Documents.zip
Typically an email attachment doesn't arrive for one of two reasons:
The path you used to load the NSData resulted in the data being nil.
The file is too large to send via email.
You have several issues leading to problem one.
The path for the zip file is in a read-only folder - the root of your app's resource bundle.
Never use NSHomeDirectory() to create paths to folders in your app's sandbox. Things changed in iOS 8 and such paths won't work at all. Only use NSSearchPathForDirectoriesInDomains with the proper folder reference such as NSDocumentDirectory.
To solve the first issue, change this:
NSString *archivePath = [documentsDirectory stringByAppendingString:#".zip"];
to something like:
NSString *archivePath = [documentsDirectory stringByAppendingPathComponent:#"SomeFiles.zip"];
It would be even better to store this temporary file in the caches folder (use NSCachesDirectory instead of NSDocumentDirectory). Then delete the file after sending the email.
Related
I'm getting base64-encoded file content from server. Then I'm writing data into file. I checked that file is not empty after that, it means data was successfully written to file. But when I'm trying to present this file, all I get is an empty view. So what am I doin' wrong?
enter image description here
[f getFile:^(NSString * _Nonnull string) {
NSString *docsDir;
NSArray *dirPaths;
NSData *content = [string dataUsingEncoding:NSUTF8StringEncoding];
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
NSString *databasePath = [[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent:#"hill.jpg"]];
[content writeToFile:databasePath atomically:YES];
if ([[NSFileManager defaultManager] fileExistsAtPath:databasePath]){
NSURL *url = [NSURL fileURLWithPath:databasePath];
UIDocumentInteractionController *documentInteractionController =[UIDocumentInteractionController interactionControllerWithURL:url];
documentInteractionController.delegate = self;
[documentInteractionController presentPreviewAnimated:YES];
}
} Error:^(NSString * _Nonnull errorMessage) {
}];
Edited your code snippet, Try it
[f getFile:^(NSString * _Nonnull string) {
NSString *docsDir;
NSArray *dirPaths;
NSData *content = [[NSData alloc] initWithBase64EncodedString: string options:0];
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
NSString *databasePath = [[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent:#"hill.jpg"]];
[content writeToFile:databasePath atomically:YES];
if ([[NSFileManager defaultManager] fileExistsAtPath:databasePath]){
NSURL *url = [NSURL fileURLWithPath:databasePath];
UIDocumentInteractionController *documentInteractionController =[UIDocumentInteractionController interactionControllerWithURL:url];
documentInteractionController.delegate = self;
[documentInteractionController presentPreviewAnimated:YES];
}
} Error:^(NSString * _Nonnull errorMessage) {
}];
From your code, I see you save a string into a an image file (hill.jpg). The UIDocumentInteractionController read file base on their extension, so they can't read this file. I think if you change your file name to hill.txt, your code could work. Hope this helps.
As you say, the content gets from the server are base64-encode, so you need to decode it.
NSData *imageContent = [[NSData alloc] initWithBase64EncodedString:string options:kNilOptions];
if (imageContent) {
// save to file
}
I am trying to attach a video to an email. It is not a local video so I write it to a file. Then I get the data from that file and attach to the email. When the email comes up, the only thing there is the file name "video.mp4" with no video.
MFMailComposeViewController *controller = [[MFMailComposeViewController alloc] init];
controller.mailComposeDelegate = self;
NSData *videoData = [NSData dataWithContentsOfURL:url];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *tempPath = [documentsDirectory stringByAppendingFormat:#"/video.mp4"];
NSLog(#"writing");
BOOL success = [videoData writeToFile:tempPath atomically:NO];
if (success){
NSError *error = nil;
NSData *data = [NSData dataWithContentsOfFile:tempPath];
NSLog(#"path: %#", tempPath);
if (error) {
NSLog(#"%#", [error localizedDescription]);
}else{
[controller addAttachmentData:data mimeType:#"video/mp4" fileName:#"video.mp4"];
NSLog(#"Data has loaded successfully.");
}
}
I think only approach to try is formatting mail as HTML. Otherwise you will always sending an attachment.
NSString *messageBody = #" /*Some HTML format containing HTML5 video player*/";
[controller setMessageBody:messageBody isHTML:YES];
So you need to look for suitable CSS and HTML tags for your video. But don't forget to test it with most e-mail clients as you may see different looks.
I am having issues getting my program to accept the path I gave it and returning it as NSData
// Get the resource path and read the file using NSData
NSString *searchFilename = #"SafetyAuditReport.pdf"; // name of the PDF you are searching for
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath:documentsDirectory];
NSString *documentsSubpath;
while (documentsSubpath = [direnum nextObject])
{
if (![documentsSubpath.lastPathComponent isEqual:searchFilename]) {
continue;
}
NSLog(#"found %#", documentsSubpath);
}
NSData *pdfData = [NSData dataWithContentsOfFile:documentsSubpath];
// Determine the MIME type
NSString *mimeType = #"application/pdf";
MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
mc.mailComposeDelegate = self;
[mc setSubject:emailTitle];
[mc setMessageBody:messageBody isHTML:NO];
[mc setToRecipients:toRecipents];
[mc addAttachmentData:pdfData mimeType:mimeType fileName:#""];
NSLog(#"data was loaded.......");
// Present mail view controller on screen
[self presentViewController:mc animated:YES completion:nil];
When ever the program gets the the emailing section it throws a nil exception for addAttachmentData:pdfData mimeType:mimeType fileName: saying the variable I gave it was nil (pdfData) when I know the file exists in the documents directory.
Thanks in advance
plz use this code
- (IBAction)sendMailWithAttachedFile
{
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
// NSURL* outputURL = [[NSURL alloc] initFileURLWithPath:[self pathForResourse:fileName ofType:extension]];
//Get the file path
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"data.pdf"];
NSURL* outputURL = [[NSURL alloc] initFileURLWithPath:path];
NSData *data=[[NSData alloc]initWithContentsOfURL:outputURL];
[picker addAttachmentData:data mimeType:#"application/pdf" fileName:#"data.pdf"];
[self presentModalViewController:picker animated:YES];
}
-(void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
[self dismissViewControllerAnimated:YES completion:nil];
}
Here is how we did it.....
NSString *path = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory,NSUserDomainMask, YES);
documentsDirectory = [paths objectAtIndex:0];
path = [[NSBundle mainBundle]pathForResource:#"Name of File" ofType:#"pdf"];
NSData *pdfData = [NSData dataWithContentsOfFile:path];
MFMailComposeViewController *mail = [[MFMailComposeViewController alloc] init];
mail.editing = YES;
mail.mailComposeDelegate = self;
[mail setSubject:#"Your subject"];
[pdfData writeToFile:path atomically:NO];
[mail addAttachmentData:pdfData mimeType:#"application/pdf" fileName:#"Name OF File.pdf"];
[self presentViewController:mail animated:YES completion:NULL];
I can able to zip the multiple pdf files and individual folder . But failed to create zip folder of a file and folder which i marked in my screenshot.here is my code . In the If condition i write the code for creating zip file for a folder and in else i write code for files . If i select one file and folder , I need to create zip file of both folder and file in single zip file .
if([[[[filePathsArray objectAtIndex:i]objectForKey:#"PdfName"] pathExtension]isEqualToString:#""]){
// For Folder - It creates a zip file in document directory .
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDirectory = [paths objectAtIndex:0];
BOOL isDir=NO;
NSArray *directoryContents = [[NSFileManager defaultManager] directoryContentsAtPath: docDirectory];
NSString *exportPath = [[mailArray objectAtIndex:i]objectForKey:#"PdfPath"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:exportPath isDirectory:&isDir] && isDir){
directoryContents = [fileManager subpathsAtPath:exportPath];
}
archivePath = [exportPath stringByAppendingString:[NSString stringWithFormat:#"%#.zip", [[filePathsArray objectAtIndex:i]objectForKey:#"PdfName"]]];
ZipArchive *archiver = [[ZipArchive alloc] init];
[archiver CreateZipFile2:archivePath];
for(NSString *path in directoryContents)
{
NSString *longPath = [exportPath stringByAppendingPathComponent:path];
if([fileManager fileExistsAtPath:longPath isDirectory:&isDir] && !isDir)
{
NSString * extension = #"pdf";
if ([[longPath pathExtension]isEqualToString:#""]||[[[longPath pathExtension]lowercaseString]isEqualToString:extension]) {
[archiver addFileToZip:longPath newname:path];
}
}
}
BOOL successCompressing = [archiver CloseZipFile2];
if(successCompressing)
NSLog(#"Success");
else
NSLog(#"Fail");
NSString *path = archivePath;
[pdfData appendData:[NSMutableData dataWithContentsOfFile: path]];
}
else{
// For Single or Multiple pdf files - It creates a zip file in document directory .
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDirectory = [paths objectAtIndex:0];
isFolder = YES;
archivePath = [docDirectory stringByAppendingString:#"/pdfMarkup.zip"];
ZipArchive *archiver = [[ZipArchive alloc] init];
[archiver CreateZipFile2:archivePath];
for (int i =0; i<[mailArray count]; i++)
{
[archiver addFileToZip:[[mailArray objectAtIndex:i]objectForKey:#"PdfPath"] newname:[[[mailArray objectAtIndex:i]objectForKey:#"PdfName"] stringByReplacingOccurrencesOfString:#"/" withString:#""]];
}
BOOL successCompressing = [archiver CloseZipFile2];
if(successCompressing)
{
NSLog(#"Zipp successfull");
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"message:#"Cannot zip Docs Folder"delegate:nilcancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
NSString *path = archivePath;
[pdfData appendData:[NSMutableData dataWithContentsOfFile: path]];
}
I have implemented the module for sending the email from my iPhone device to server. When it comes to the implementation, there is no email file attach instead. I sweared I have added the attACHMENT . THE below is my working
-(IBAction)sendMail:(id)sender{
NSArray *toRecipents = [NSArray arrayWithObjects:#"birth.lo#sdsdfsfsdf-hk.com",#"jason.li#asdasdad-hk.com",#"lo.sdad#gmail.com",nil];
mailComposer = [[MFMailComposeViewController alloc]init];
if ([MFMailComposeViewController canSendMail]) {
mailComposer.mailComposeDelegate = self;
[mailComposer setSubject:#"NOXAV testing"];
[mailComposer setToRecipients:toRecipents] ;
[mailComposer setMessageBody:#"Testing message for the test mail" isHTML:NO];
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//make a file name to write the data to using the documents directory:
NSString *fileName = [NSString stringWithFormat:#"%#/textfile.txt",
documentsDirectory];
NSData *fileData = [NSData dataWithContentsOfFile:fileName];
NSString *mimeType = #"text/html";
[mailComposer addAttachmentData:fileData mimeType:mimeType fileName:fileName];
[self presentModalViewController:mailComposer animated:YES ];
}
}
-(void)mailComposeController:(MFMailComposeViewController *)controller
didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error{
if (result) {
NSLog(#"Result : %d",result);
}
if (error) {
NSLog(#"Error : %#",error);
}
[self dismissModalViewControllerAnimated:YES];
}
The MIME type for text file should be text/plain,So change
NSString *mimeType = #"text/html";
to
NSString *mimeType = #"text/plain";
Edit
Also change the fileName here
[mailComposer addAttachmentData:fileData mimeType:mimeType fileName:#"textfile.txt"];
Looks like file name problem, change following statement along with above suggested by Yogesh -
//make a file name to write the data to using the documents directory:
NSString * fileName = [documentsDirectory stringByAppendingPathComponent:#"textfile.txt"];
NSData *fileData = [NSData dataWithContentsOfFile:fileName];
NSString *mimeType = #"text/plain";
Your fileData may not be getting the data from file. Check if [filedata length] = some value.