How to create zip of folder and file in IOS? - ios

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]];
}

Related

Data storing issue into plist file

Once plist is created data storing start automatically, but after some time it automatically stop storing data in plist. But once when i kill app and restart again, it will start again as previously mention and cycle goes on...
Here is my code
- (void)saveLocationsToPlist:(NSMutableDictionary*)mdictPlist {
NSString *plistName = [NSString stringWithFormat:#"LocationArray.plist"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
NSString *fullPath = [NSString stringWithFormat:#"%#/%#", docDir, plistName];
NSMutableDictionary *savedProfile = [[NSMutableDictionary alloc] initWithContentsOfFile:fullPath];
NSLog(#"ADD LOCATION TIME : %#",[NSDate date]);
NSLog(#"ADD LOCATION DATA : %#",mdictPlist);
if (![[NSFileManager defaultManager] fileExistsAtPath:fullPath]){
BFLog(#"applicationDocumentsDir Not exists");
fullPath = [docDir stringByAppendingPathComponent: [NSString stringWithFormat:#"LocationArray.plist"] ];
}
if (!savedProfile) {
savedProfile = [[NSMutableDictionary alloc] init];
self.myLocationArrayInPlist = [[NSMutableArray alloc]init];
} else {
self.myLocationArrayInPlist = [savedProfile objectForKey:#"LocationArray"];
}
if(mdictPlist) {
if(self.myLocationArrayInPlist == nil){
self.myLocationArrayInPlist = [[NSMutableArray alloc]init];
}
[_myLocationArrayInPlist addObject:mdictPlist];
[savedProfile setObject:_myLocationArrayInPlist forKey:#"LocationArray"];
}
if (![savedProfile writeToFile:fullPath atomically:FALSE]) {
BFLog(#"Couldn't save LocationArray.plist savedProfile :- %# \n Location Data :- %# \n fullPath:-%#",savedProfile,mdictPlist,fullPath);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSFileManager *fm = [NSFileManager defaultManager];
NSString *directory = [documentsDirectoryPath stringByAppendingPathComponent:#""];
NSError *error = nil;
for (NSString *file in [fm contentsOfDirectoryAtPath:directory error:&error]) {
NSLog(#"%#",[NSString stringWithFormat:#"%#/%#", directory, file]);
if([file isEqualToString:#"LocationArray.plist"]){
BOOL success = [fm removeItemAtPath:[NSString stringWithFormat:#"%#/%#", directory, file] error:&error];
if (!success || error) {
// it failed.
BFLog(#"Delete error : %#",error);
}
else {
[self saveLocationsToPlist:myLocationDictInPlist];
}
}
}
}
}
Any idea about this issue.

How can I backup and restore .zip file on iCloud Drive?

I want to store .zip files on iCloud. Anybody help me how to upload and restore? I have read the Apple guideline for iCloud backup and now I have created one folder with some files and two folders with multiple images and then generate zip file of that folder.
First Save your File and Folder on Local Storage.
Then Create this File & Folder's Zip File.
And Last Upload Your zip file on iCloud.
For get this file doing reverse process.
- (void)viewDidLoad {
[super viewDidLoad];
[self CreatFileAndFolder];
}
Create Folder on local and save file in this folder that you want upload on iCloud Drive.
-(void)CreatFileAndFolder{
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"/meetInChat"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];
NSString *stringToWrite = #"1\n2\n3\n41\n2\n3\n41\n2\n3\n41\n2\n3\n41\n2\n3\n41\n2\n3\n41\n2\n3\n41\n2\n3\n41\n2\n3\n41\n2\n3\n41\n2\n3\n41\n2\n3\n41\n2\n3\n41\n2\n3\n41\n2\n3\n41\n2\n3\n4";
NSString *exportPath = [dataPath stringByAppendingString:#"/mytext.txt"];
[stringToWrite writeToFile:exportPath atomically:YES encoding:NSUTF8StringEncoding error:&error];
}
Create Action that First Create Zip file your Folder and then Upload your Zip file on iCloud Drive.
-(IBAction) iCloudSyncing:(id)sender
{
[self zipFolder];
//--------------------------Zip Folder Upload on iCloud-----------------------------//
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *zipFilePath = [documentsDirectory stringByAppendingPathComponent:#"meetInChat.zip"];
NSLog(#"FilePath=>%#",zipFilePath);
NSURL *u = [[NSURL alloc] initFileURLWithPath:zipFilePath];
NSData *data = [[NSData alloc] initWithContentsOfURL:u];
NSURL *ubiq = [[NSFileManager defaultManager]URLForUbiquityContainerIdentifier:nil];
NSURL *ubiquitousPackage = [[ubiq URLByAppendingPathComponent:#"Documents"]URLByAppendingPathComponent:#"meetInChat.zip"];
Mydoc = [[MyDocument alloc] initWithFileURL:ubiquitousPackage];
Mydoc.zipDataContent = data;
[Mydoc saveToURL:[Mydoc fileURL] forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success)
{
if (success)
{
NSLog(#"PictureZip: Synced with icloud");
[[NSUbiquitousKeyValueStore defaultStore]setData:data forKey:#"meetInChat"];
}
else
NSLog(#"PictureZip: Syncing FAILED with icloud");
}];
}
Create Zip file from your folder
-(BOOL)zipFolder
{
//--------------------------Create Zip Folder -----------------------------//
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDirectory = [paths objectAtIndex:0];
BOOL isDir=NO;
NSArray *subpaths = nil;
NSString *exportPath = [docDirectory stringByAppendingString:#"/meetInChat"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:exportPath isDirectory:&isDir] && isDir){
subpaths = [fileManager subpathsAtPath:exportPath];
}
NSString *meetInChatPath = [docDirectory stringByAppendingString:[NSString stringWithFormat:#"/%#.zip",#"meetInChat"]];
ZipArchive *archiver = [[ZipArchive alloc] init];
[archiver CreateZipFile2:meetInChatPath];
if (isDir) {
for(NSString *path in subpaths){
NSString *fullPath = [exportPath stringByAppendingPathComponent:path];
if([fileManager fileExistsAtPath:fullPath isDirectory:&isDir] && !isDir){
[archiver addFileToZip:fullPath newname:path];
}
}
} else {
[archiver addFileToZip:exportPath newname:#"meetInChat"];
}
BOOL successCompressing = [archiver CloseZipFile2];
if(successCompressing)
return YES;
else
return NO;
}
Here Get ZipFile back From iCloud Drive then Doing reverse process Unzip your file and get data back.
- (IBAction)GetData:(id)sender {
//--------------------------Get data back from iCloud -----------------------------//
id token = [[NSFileManager defaultManager] ubiquityIdentityToken];
if (token == nil)
{
NSLog(#"ICloud Is not LogIn");
}
else
{
NSLog(#"ICloud Is LogIn");
NSData *dataFile = [[NSUbiquitousKeyValueStore defaultStore]dataForKey:#"meetInChat"];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* fileName = [NSString stringWithFormat:#"meetInChat.zip"];
NSString* fileAtPath = [documentsDirectory stringByAppendingPathComponent:fileName];
[dataFile writeToFile:fileAtPath atomically:NO];
}
}

How to add multiple Documents in a zip file in iOS?

I want make a zip file containing multiple documents, documents are taken from my Document Directory.
BOOL isDir=NO;
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSArray *subpaths;
for(int i=0; i<[arrdocument count]; i++)
{
NSString *toCompress = [arrdocument objectAtIndex:i];
NSString *pathToCompress = [documentsDirectory stringByAppendingPathComponent:toCompress];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:pathToCompress isDirectory:&isDir] && isDir){
subpaths = [fileManager subpathsAtPath:pathToCompress];
} else if ([fileManager fileExistsAtPath:pathToCompress]) {
subpaths = [NSArray arrayWithObject:pathToCompress];
}
NSString *zipFilePath = [documentsDirectory stringByAppendingPathComponent:#"myZipFileName2.zip"];
ZipArchive *za = [[ZipArchive alloc] init];
[za CreateZipFile2:zipFilePath];
if (isDir) {
for(NSString *path in subpaths){
NSString *fullPath = [pathToCompress stringByAppendingPathComponent:path];
if([fileManager fileExistsAtPath:fullPath isDirectory:&isDir] && !isDir){
[za addFileToZip:fullPath newname:path];
}
}
} else {
[za addFileToZip:pathToCompress newname:toCompress];
}
}
But when I look at the zip file it shows only one document inside the zip file?
It seems like you recreate the zip file in each loop iteration. You should instead move the creation of the zip file out of the loop or just specify appending when you create the zip file like this:
[za CreateZipFile2:zipFilePath append:YES];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *zipFile = [documentsDirectory stringByAppendingPathComponent:#"compressed.zip"];
ZipArchive *zip = [[ZipArchive alloc] init];
BOOL result = [zip CreateZipFile2:zipFile];
if(result){
NSError *error;
NSArray *allFiles = arrdocument;
for(int index = 0; index<allFiles.count; index++){
id singleFileName = [allFiles objectAtIndex:index];
NSString *singleFilePath = [documentsDirectory stringByAppendingPathComponent:singleFileName];
[zip addFileToZip:singleFilePath newname:singleFileName];
}
[zip CloseZipFile2];
}else{
[self showErrorMessage:#"Unable to to create zip file. Please try again later" withTitle:#"Error"];
}

Zip the doc file in ios and save in to document directory

I would like to save a doc file into a zip file in the document directory and when the user chooses they can attach it in an email. I have created the zip file but when I want to open it again it creates a zipfile, zip.cpgz instead of testing.zip .
Here is my code for creating the zip file
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory error:nil];
int index =0;
for (NSString *item in filePathsArray){
if ([[item pathExtension] isEqualToString:#"doc"])
{
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[filePathsArray objectAtIndex:index]];
//NSString *FileName=[stringPath1 stringByAppendingPathComponent:#"Console.doc"];
NSString *stringPath=[documentsDirectory stringByAppendingPathComponent:[#"testing" stringByAppendingFormat:#".zip"]];
ZipFile *zipFile = [[ZipFile alloc]initWithFileName:stringPath mode:ZipFileModeCreate];
ZipWriteStream *stream= [zipFile writeFileInZipWithName:#"doc" compressionLevel:ZipCompressionLevelBest];
NSData *data = [NSData dataWithContentsOfFile:filePath];
[stream writeData:data];
[stream finishedWriting];
}
}
You must use ssziparchive
An Utility class for zipping and unzipping files for iOS
Example provided:-
// Unzipping
NSString *zipPath = #"path_to_your_zip_file";
NSString *destinationPath = #"path_to_the_folder_where_you_want_it_unzipped";
[SSZipArchive unzipFileAtPath:zipPath toDestination:destinationPath];
// Zipping
NSString *zippedPath = #"path_where_you_want_the_file_created";
NSArray *inputPaths = [NSArray arrayWithObjects:
[[NSBundle mainBundle] pathForResource:#"photo1" ofType:#"jpg"],
[[NSBundle mainBundle] pathForResource:#"photo2" ofType:#"jpg"]
nil];
[SSZipArchive createZipFileAtPath:zippedPath withFilesAtPaths:inputPaths];

Zip file doesn't arrive when attached to email

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.

Resources