How to add multiple Documents in a zip file in iOS? - 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"];
}

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

Retrieve files from Dirrectory

My Application creates Png, Pdf, and Jpg files and stores in Documentary with different name formats. How can i retrieve all filetypes at a time. For example If i want to count how many number of pdf files in documentary, where all files exists and i have to count only pdf files. How can i achieve this for particular file types.
NSFileManager *filemanage = [NSFileManager defaultManager];
NSArray *docPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSArray *filelist= [filemanage contentsOfDirectoryAtPath:[docPaths objectAtIndex:0] error:nil];
NSInteger filescount = [filelist count];
NSString *filesnumber = [NSString stringWithFormat:#"%d", filescount];
NSLog(#"filesnumber:%#", filesnumber);
fileLabel.text = filesnumber;
NSFileManager *filemanage = [NSFileManager defaultManager];
NSArray *docPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSArray *filelist= [filemanage contentsOfDirectoryAtPath:[docPaths objectAtIndex:0] error:nil];
NSInteger filescount = 0;
for (NSString *fileName in filelist) {
if ([[fileName pathExtension] isEqualToString:#"pdf"]) {
filescount++;
}
}
NSString *filesnumber = [NSString stringWithFormat:#"%d", filescount];
NSLog(#"filesnumber:%#", filesnumber);
fileLabel.text = filesnumber;
You could || the if statement to add .jpg, .png and whatever else you may want.
NSFileManager *filemanage = [NSFileManager defaultManager];
NSArray *docPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSArray *filelist = [filemanage contentsOfDirectoryAtPath:[docPaths objectAtIndex:0] error:nil];
NSInteger fileCountPDF = 0;
for (NSString *fileName in filelist) {
NSString *extension = fileName.pathExtension;
if ([extension caseInsensitiveCompare:#"pdf"] == NSOrderedSame) {
NSLog(#"PDF file found");
fileCountPDF++;
}
}
NSLog(#"PDF files: %d",fileCountPDF);
//...

How to create zip of folder and file in 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]];
}

.DS_Store file skipping

In my application I Use NSFileManager to get the number of files in a folder using following code
NSFileManager *manager=[NSFileManager defaultManager];
NSString *path;
int numberofFiles=[[manager contentsOfDirectoryAtPath:path error:nil] count];
numberofFiles=numberofFiles-1; //number of files except .DS_Store
But my problem is that the file .DS_Store is not always created defaultly, at that time I get less count than the count of files actually present in that directory .
So is there a method in NSFileManager which return the array of files excluding .DS_Store
or I have to exclude manually using -IsEqualToString method
or else is there any option to create a new directory without .DS_Store file.
Explicitly look for the .DS_Store file and adjust the count if it's found:
NSFileManager *manager=[NSFileManager defaultManager];
NSString *path = ...; // Presumably this is a valid path?
NSArray *contents = [manager contentsOfDirectoryAtPath:path error:nil];
NSUInteger numberOfFiles = [contents count];
if ([contents indexOfObject:#".DS_Store"] != NSNotFound)
numberOfFiles--;
Try this.. Its working for me..
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSFileManager *manager = [NSFileManager defaultManager];
NSArray *imageFilenames = [manager contentsOfDirectoryAtPath:documentsDirectory error:nil];
for (int i = 0; i < [imageFilenames count]; i++)
{
NSString *imageName = [NSString stringWithFormat:#"%#/%#",documentsDirectory,[imageFilenames objectAtIndex:i] ];
if (![[imageFilenames objectAtIndex:i]isEqualToString:#".DS_Store"])
{
UIImage *myimage = [UIImage imageWithContentsOfFile:imageName];
UIImageView *imageView = [[UIImageView alloc] initWithImage:_myimage];
}
}

Resources