Creating zip files in ObjectiveC for iPhone - iphone

Is it possible to create .zip files in objective C ?
Any libraries available or suggestions ?

first you download Objective-zip example from http://code.google.com/p/objective-zip/downloads/list
in this example Find and copy three folder Objective-Zip, MiniZip and ZLib drag in to your project
import two class in you .m class
"ZipFile.h" and
"ZipWriteStream.h"
create method of zip my code is :-
-(IBAction)Zip{
self.fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory , NSUserDomainMask, YES);
NSString *ZipLibrary = [paths objectAtIndex:0];
NSString *fullPathToFile = [ZipLibrary stringByAppendingPathComponent:#"backUp.zip"];
//[self.fileManager createDirectoryAtPath:fullPathToFile attributes:nil];
//self.documentsDir = [paths objectAtIndex:0];
ZipFile *zipFile = [[ZipFile alloc]initWithFileName:fullPathToFile mode:ZipFileModeCreate];
NSError *error = nil;
self.fileManager = [NSFileManager defaultManager];
NSArray *paths1 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
self.documentsDir = [paths1 objectAtIndex:0];
NSArray *files = [[NSFileManager defaultManager]contentsOfDirectoryAtPath:self.documentsDir error:&error];
//for(NSString *filename in files){
for(int i = 0;i<files.count;i++){
id myArrayElement = [files objectAtIndex:i];
if([myArrayElement rangeOfString:#".png" ].location !=NSNotFound){
NSLog(#"add %#", myArrayElement);
NSString *path = [self.documentsDir stringByAppendingPathComponent:myArrayElement];
NSDictionary *attributes = [[NSFileManager defaultManager]attributesOfItemAtPath:path error:&error];
NSDate *Date = [attributes objectForKey:NSFileCreationDate];
ZipWriteStream *streem = [zipFile writeFileInZipWithName:myArrayElement fileDate:Date compressionLevel:ZipCompressionLevelBest];
NSData *data = [NSData dataWithContentsOfFile:path];
// NSLog(#"%d",data);
[streem writeData:data];
[streem finishedWriting];
}else if([myArrayElement rangeOfString:#".txt" ].location !=NSNotFound)
{
NSString *path = [self.documentsDir stringByAppendingPathComponent:myArrayElement];
NSDictionary *attributes = [[NSFileManager defaultManager]attributesOfItemAtPath:path error:&error];
NSDate *Date = [attributes objectForKey:NSFileCreationDate];
ZipWriteStream *streem = [zipFile writeFileInZipWithName:myArrayElement fileDate:Date compressionLevel:ZipCompressionLevelBest];
NSData *data = [NSData dataWithContentsOfFile:path];
// NSLog(#"%d",data);
[streem writeData:data];
[streem finishedWriting];
}
}
[self testcsv];
[zipFile close];
}
your documents directory saved item .png and .txt files zipping in Library folder with backup.zip
i hope this is helps

BEfore someone mentions http://code.google.com/p/ziparchive/ .. I evaluated that code and it is pretty terrible. I ended up using it for a quick demo hack that had to do but I would never use it in production. ZipKit http://bitbucket.org/kolpanic/zipkit/wiki/Home seems to be in much better shape.

NSString *stringPath1 = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]];
NSString *FileName=[stringPath1 stringByAppendingPathComponent:#"Your file name"];
NSString *stringPath=[stringPath1 stringByAppendingPathComponent:[#"Your file name" stringByAppendingFormat:#".zip"]];
NSArray *files = [[NSFileManager defaultManager]contentsOfDirectoryAtPath:FileName error:&error];
ZipFile *zipFile = [[ZipFile alloc]initWithFileName:stringPath mode:ZipFileModeCreate];
for(int i = 0;i<files.count;i++){
id myArrayElement = [files objectAtIndex:i];
NSLog(#"add %#", myArrayElement);
NSString *path = [FileName stringByAppendingPathComponent:myArrayElement];
NSDictionary *attributes = [[NSFileManager defaultManager]attributesOfItemAtPath:path error:&error];
NSDate *Date = [attributes objectForKey:NSFileCreationDate];
ZipWriteStream *streem = [zipFile writeFileInZipWithName:myArrayElement fileDate:Date compressionLevel:ZipCompressionLevelBest];
NSData *data = [NSData dataWithContentsOfFile:path];
[streem writeData:data];
[streem finishedWriting];
}
[zipFile close];

Related

Cannot read/write from/to plist on device, but can in simulator

i've been looking at a lot of posts with a similar problem here on Stackoverflow, but i still cannot figure out why i can't write/read my plist.
Here is my method to load my plist into the app.
This should copy the plist to the device's documents folder and not resources folder, correct?
-(void)loadPlist:(NSString*)plistString {
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.plist", plistString]];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:path]) {
NSString *bundle = [[NSBundle mainBundle]pathForResource:plistString ofType:#"plist"];
[fileManager copyItemAtPath:bundle toPath:path error:&error];
} else {
NSLog(#"%# already exists",path);
}
}
This is how i write to my plist:
-(void)writeScore:(NSString*)objectstring forPlayer:(int)playerTag {
switch (playerTag) {
case 1:
NSLog(#"Wrote to 1");
holeInt = [P1hole_Label.text integerValue];
plistpath = [[NSBundle mainBundle]pathForResource:#"Scores" ofType:#"plist"];
plistdata = [[NSMutableDictionary alloc]initWithContentsOfFile:plistpath];
[plistdata setObject:[NSString stringWithString:objectstring] forKey:[NSString stringWithFormat:#"Hole %i", holeInt]];
[plistdata writeToFile:plistpath atomically:YES];
break;
Etc.
And here is how i read the plist:
-(void)createNewHoleLabel:(NSString*)plistString andSetX:(int)x {
//SetX; 0 = P1, 1 = P2 etc.
UILabel *label = [UILabel new];
[label setFrame:CGRectMake(80 + 53 * x, 93 + 26 * integer, 50, 25)];
NSString *path = [[NSBundle mainBundle]pathForResource:plistString ofType:#"plist"];
NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithContentsOfFile:path];
label.text = [dict objectForKey:[NSString stringWithFormat:#"Hole %i", integer + 1]];
[label setAdjustsFontSizeToFitWidth:YES];
[label setTextAlignment:NSTextAlignmentCenter];
integer++;
[scrollview addSubview:label];
}
I hope you can help me. Please ask for further details if needed.
In writeScore:forPlayer:
plistpath = [[NSBundle mainBundle]pathForResource:#"Scores" ofType:#"plist"];
...
[plistdata writeToFile:plistpath atomically:YES];
You are trying to write to the the App's bundle which can not be done on the device. You should be writing the the Documents directory.

Creating folder and adding multiple images

I'm creating an iPhone app where I need to create separate folder and add images in those folder and upload that whole folder on google drive. How can i create folder and images to it.
Thanks in advance
Creating A Folder
NSString *pngPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:[NSString stringWithFormat:#"/WB/%#",self.viewIndex]];
// Check if the directory already exists
BOOL isDir;
BOOL exists = [[NSFileManager defaultManager] fileExistsAtPath:pngPath isDirectory:&isDir];
if (exists)
{
if (!isDir)
{
NSError *error = nil;
[[NSFileManager defaultManager] removeItemAtPath:pngPath error:&error];
// Directory does not exist so create it
[[NSFileManager defaultManager] createDirectoryAtPath:pngPath withIntermediateDirectories:YES attributes:nil error:nil];
}
}
else
{
// Directory does not exist so create it
[[NSFileManager defaultManager] createDirectoryAtPath:pngPath withIntermediateDirectories:YES attributes:nil error:nil];
}
Adding Images to that Folder
NSString *pngImagePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:[NSString stringWithFormat:#"/WB/%#/%d.png",self.viewIndex,lineIndex]];
UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, 1.0);
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
self.curImage = UIGraphicsGetImageFromCurrentImageContext();
[UIImagePNGRepresentation(self.curImage) writeToFile:pngImagePath atomically:YES];
UIGraphicsEndImageContext();
Try this :
//For save to Document Directory
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-dd"];
NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setDateFormat:#"HH:mm:ss"];
NSDate *now = [[NSDate alloc] init];
NSString *theDate = [dateFormat stringFromDate:now];
NSString *theTime = [timeFormat stringFromDate:now];
NSString *strImageName=[NSString stringWithFormat:#"Documents/MyPhotos/Dt%#%#.png",theDate,theTime];
strImageName=[strImageName stringByReplacingOccurrencesOfString:#"-" withString:#""];
strImageName=[strImageName stringByReplacingOccurrencesOfString:#":" withString:#""];
[self createDocumentDirectory:#"MyPhotos"];
NSString *pngPath = [NSHomeDirectory() stringByAppendingPathComponent:strImageName];
[UIImagePNGRepresentation(YourImageView.image) writeToFile:pngPath atomically:YES];
-(void)createDocumentDirectory:(NSString*)pStrDirectoryName
{
NSString *dataPath = [self getDocumentDirectoryPath:pStrDirectoryName];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:NULL];
}
-(NSString*)getDocumentDirectoryPath:(NSString*)pStrPathName
{
NSString *strPath = #"";
if(pStrPathName)
strPath = [[kAppDirectoryPath objectAtIndex:0] stringByAppendingPathComponent:pStrPathName];
return strPath;
}
//Get Photo Onebyone
NSError *error = nil;
NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[self getDocumentDirectoryPath:#"MyPhotos"] error:&error];
if (!error) {
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"self ENDSWITH '.png'"];
NSArray *imagesOnly = [dirContents filteredArrayUsingPredicate:predicate];
for (int i=0;i<[imagesOnly count]; i++) {
[arrSaveImage addObject:[imagesOnly objectAtIndex:i]];//Save in your array.
}
}

Get document directory files date modified time in iphone

NSArray *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *currDircetory = [documentPath objectAtIndex:0];
NSArray *filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:currDircetory error:nil];
for (NSString *s in filePathsArray){
NSLog(#"file %#", s);
}
Now i used the above code to get list of file from document directory now i want to know how to get modified time of the file in document directory.
Thanks,
Vijayan
You can use this :
NSArray *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *currDircetory = [documentPath objectAtIndex:0];
NSArray *filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:currDircetory error:nil];
for (NSString *s in filePathsArray){
NSString *filestring = [currDircetory stringByAppendingFormat:#"/%#",s];
NSDictionary *filePathsArray1 = [[NSFileManager defaultManager] attributesOfItemAtPath:filestring error:nil];
NSLog(#"Modified Day : %#", [filePathsArray1 objectForKey:NSFileModificationDate]);
}
NSFileManager* filemngr = [NSFileManager defaultManager];
NSDictionary* attributes = [filemngr attributesOfItemAtPath:path error:nil];
if (attributes != nil) {
NSDate *date = (NSDate*)[attributes objectForKey:NSFileModificationDate];
} else {
NSLog(#"File Not found !!!");
}
You can get your answer Here.
But only change you going to do is, you need to change NSFileCreationDate to NSFileModificationDate
NSDate *date = (NSDate*)[attrs objectForKey: NSFileModificationDate];

How to retrieve UIImage from particular folder in document directory in iPhone

I have used the below function to store images locally in a folder created in document directory
NSError *error;
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
// FOR STORING IMAGE INTO FOLDER CREATED IN DOCUMENT DIRECTORY
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"/ImagesFolder"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];
NSData* imageData = UIImagePNGRepresentation(imageView.image);
NSString* incrementedImgStr = [NSString stringWithFormat:#"Image%d.png",delegate.dirCountImages];
NSString* fullPathToFile2 = [dataPath stringByAppendingPathComponent:incrementedImgStr];
[imageData writeToFile:fullPathToFile2 atomically:NO];
However how do i retrieve images from that particular folder in document directory
-(NSMutableArray*)getPhotoFileNames:(NSString*)parentFolderName
{
NSString *path = [NSString stringWithFormat:#"%#/%#",[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES)objectAtIndex:0], parentFolderName];
NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:nil];
NSEnumerator *enumerator = [dirContents objectEnumerator];
id fileName;
NSMutableArray *fileArray = [[NSMutableArray alloc] init];
while (fileName = [enumerator nextObject])
{
NSString *fullFilePath = [path stringByAppendingPathComponent:fileName];
NSRange textRangeJpg = [[fileName lowercaseString] rangeOfString:[#".png" lowercaseString]];
if (textRangeJpg.location != NSNotFound)
{
UIImage *originalImage = [UIImage imageWithContentsOfFile:fullFilePath];
[fileArray addObject:originalImage];
}
}
return fileArray;
}
Just need to have the full path and use this method. [[UIImage alloc]initWithContentsOfFile: <#path#>] remember to release the image after if you are not using ARC.
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(100,100,100,100)];
imageView.image = [[UIImage alloc] initWithData:myImage];
[myView addSubview:imageView];
or see that link http://www.iphonedevsdk.com/forum/iphone-sdk-development/23840-placing-image-url-image-view.html
Perhaps this will help you.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
documentsDirectory = [documentsDirectory stringByAppendingPathComponent:#"Images"];
documentsDirectory = [documentsDirectory stringByAppendingPathComponent:#"Image.png"];
[cell.songImageView setImage:[UIImage imageWithContentsOfFile:documentsDirectory]];

unable to read/write data to .plist file in iPhone

i am new to iPhone developer, i am creating ePub reader for reading ePub files.
I have plist in my iphone app and I want to read and write data to my .plist file, in which i am facing problem.
here is my code snippet,
Logic: first i am downloading an ePub file, .ePub file will be downloaded to this path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
NSLog(#"basePath=%#",basePath);
output :-
=/Users/krunal/Library/Application Support/iPhone Simulator/5.1/Applications/6B7FCD58-EDF9-44F4-8B33-5F3542536F92/Documents
now, i want to write name of Downloaded .ePubfile into file into my .plist
code:
NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile: basePath];
[data setObject:[NSNumber numberWithInt:value] forKey:#"value"];
[data writeToFile: plistPath atomically:YES];
[data release];
i tried this, but i am unable to write in my .plist file.
Any Help Will be Appriciated.
Thanks In Advance !!
Did you mean:
NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile: plistPath];
?
untested code follows:
Step 1: Copy the file to it's folder.
NSError *error1;
BOOL resourcesAlreadyInDocumentsDirectory;
BOOL copied1;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath1 = [documentsDirectory stringByAppendingString:#"/epub.plist"];
resourcesAlreadyInDocumentsDirectory = [fileManager fileExistsAtPath:filePath1];
if(resourcesAlreadyInDocumentsDirectory == YES) {
} else {
NSString *path1 = [[[NSBundle mainBundle] resourcePath] stringByAppendingFormat:#"/epub.plist"];
copied1 = [fileManager copyItemAtPath:path1 toPath:filePath1 error:&error1];
if (!copied1) {
NSAssert1(0, #"Failed to copy epub.plist. Error %#", [error1 localizedDescription]);
}
}
Step 2:Open it
NSMutableDictionary* dict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath1];
Step 3:Write data to it
[dict setObject:[NSNumber numberWithInt:value] forKey:#"value"];
[dict writeToFile:path atomically:YES];
NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile: basePath];
data is nil here, you should init it with:
NSMutableDictionary *data = [[NSMutableDictionary alloc] init];
Edited my answer to be more clear:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
if ( basePath == nil ) {
return
}
NSMutableDictionary *data = [[NSMutableDictionary alloc] init];
[data setObject:[NSNumber numberWithInt:value] forKey:#"value"];
NSString *plistPath = [NSString stringWithFormat:#"%#/name.plist", basePath];
[data writeToFile: plistPath atomically:YES];
[data release];
It is easer for you to use NSUserDefault, you data will be saved to a plist file as following code:
- (void)setOverviewGroupInstrument:(BOOL)isGroupded {
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:[Your array] forKey:[Your Key]];
[prefs synchronize];
}
Then you can read by:
- (NSMutableArray*)getOverviewInstrumentList {
return [prefs objectForKey:[Your Key]];
}