Creating folder and adding multiple images - iphone

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.
}
}

Related

Compare NSFileModificationDate of previous Backup

Here am creating backup of my database. But i don want to jus keep creating backups. i need to check the NSModificationDate property of the most recently created backup database and have to create new backup only if the database is modified. Can anyone help me on this.
-(IBAction)createdb:(id)sender
{
DatabaseList = [[NSMutableArray alloc]init];
NSDate *currentDateTime = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MMddyyyyHHmmss"];
NSString *dateInStringFormated = [dateFormatter stringFromDate:currentDateTime];
dbNameString = [NSString stringWithFormat:#"UW_%#.db",dateInStringFormated];
NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentFolderPath = [searchPaths objectAtIndex: 0];
NSString *dbName = #"UnitWiseDB.db";
NSString *dbPath1 = [documentFolderPath stringByAppendingPathComponent:dbNameString];
NSString *backupDbPath = [documentFolderPath stringByAppendingPathComponent:dbName];
NSError *error = nil;
NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:backupDbPath error:&error];
NSLog(#"Persistent store size: %# bytes", [fileAttributes objectForKey:NSFileSize]);
NSLog(#"Modification Date: %# ",[fileAttributes objectForKey:NSFileModificationDate]);
if ( ![[NSFileManager defaultManager] fileExistsAtPath:dbPath1])
{
[[NSFileManager defaultManager] copyItemAtPath:backupDbPath toPath:dbPath1 error:nil];
}
NSLog(#"DBPath.......%#",dbPath1);
NSFileManager *manager = [NSFileManager defaultManager];
NSArray *fileList = [manager contentsOfDirectoryAtPath:documentFolderPath error:nil];
for (NSString *s in fileList)
{
NSLog(#"Backup.....%#", s);
[DatabaseList addObject:s];
}
[ListViewTableView reloadData];
}
Instead of checking modification , you can use a simple trick as described by trojanfoe.
When ever you are modifying i mean adding/ removing/ editing any record in database , set a BOOL flag = YES and store in NSUSERDEFAULTS , after creating the backup, set the flag to NO.

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 avoid overwriting files on iPhone Documents folder?

I need to write files containing NSArrays into the Documents folder of my iPhone application. Next time I need to create a new file, not overwriting the previous one.
I tried like this, but it only writes doc0 and doc1.
allDocs in an NSArray declared elsewhere.
What's wrong? Thank you!
NSString *myDoc;
NSString *temp;
for (int i = 0; i < [allDocs count]; ++i){
NSFileManager* fileMgr = [NSFileManager defaultManager];
myDoc = [NSString stringWithFormat:#"doc%d.dat", i];
NSString* currentFile = [documentsDirectory stringByAppendingPathComponent:myDoc];
BOOL fileExists = [fileMgr fileExistsAtPath:currentFile];
if (fileExists == NO){
temp = [NSString stringWithFormat:#"doc%d.dat", i];
break;
} else {
temp = [NSString stringWithFormat:#"doc%d.dat",i++];
break;
}
}
NSString *myArray = [documentsDirectory stringByAppendingPathComponent:myDoc];
NSMutableArray *myMutableArray = [[NSMutableArray alloc] initWithContentsOfFile: myArray];
if(myMutableArray == nil)
{
myMutableArray = [[NSMutableArray alloc] initWithCapacity:10];
myMutableArray = anotherArray;
}
[myMutableArray writeToFile:myArray atomically:YES];
You break out of the for loop on the first iteration each time whether the file is found or not. You should be looping with incremented values for i until fileExists is false.
- (BOOL) workFileExists:(NSString *)name {
NSFileManager *fm = [NSFileManager defaultManager];
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString *filename = [name stringByAppendingString:#".swrk"];
return [fm fileExistsAtPath:[path stringByAppendingPathComponent:filename]];
}
- (NSString *)uniqueUntitledName {
NSString *untitled = #"Untitled";
NSString *name = untitled;
int i = 1;
while ([self workFileExists:name]) {
name = [NSString stringWithFormat:#"%#%d", untitled, i];
i++;
}
return name;
}
UIImage *imageForShare = [UIImage imageNamed:#"anyImage.jpg"];
NSString *stringPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:#"New Folder"];
// New Folder is your folder name
NSError *error = nil;
//in this method you are checking the path is exist or not for Folder Name
if (![[NSFileManager defaultManager] fileExistsAtPath:stringPath])
[[NSFileManager defaultManager] createDirectoryAtPath:stringPath withIntermediateDirectories:NO attributes:nil error:&error];
//now checking the image name already exist or not
NSString *fileName = [stringPath stringByAppendingFormat:#"/image.jpg"];
if (![[NSFileManager defaultManager] fileExistsAtPath:fileName])
{
NSLog(#"Path is available.");
NSData *data = UIImageJPEGRepresentation(imageForShare, 1.0);
[data writeToFile:fileName atomically:YES];
}
else
{
NSLog(#"Path doesn't exist, same name of image is already exist.");
}
Thank You!!

Cannot create URL in application support directory for caf file

When I write this code it work will
NSString *recordFile = [NSTemporaryDirectory() stringByAppendingPathComponent: (NSString*)inRecordFile];
NSLog(#"////////////////////////// recordFile /////////////////////");
NSLog(recordFile) ;
url = CFURLCreateWithString(kCFAllocatorDefault, (CFStringRef)recordFile, NULL);
// create the audio file
XThrowIfError(AudioFileCreateWithURL(url, kAudioFileCAFType, &mRecordFormat, kAudioFileFlags_EraseFile,
&mRecordFile), "AudioFileCreateWithURL failed");
CFRelease(url);
but when I change recordFile to be such that
NSString* Dpath ;
NSArray * paths;
// Build the Directory
paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
Dpath = [paths objectAtIndex:0];
Dpath = [DICOMpath stringByAppendingPathComponent:#"YYYYYYYYYYYY"];
Dpath = [DICOMpath stringByAppendingPathComponent:[FirstDirectory stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]]] ;
Dpath = [DICOMpath stringByAppendingPathComponent:[SecondtDirectory stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]]];
Dpath = [DICOMpath stringByAppendingPathComponent:#"XXX"];
NSString *recordFile = [Dpath stringByAppendingPathComponent:inRecordFile];
I see the message AudioFileCreateWithURL failed in the console, what's wrong in my code, am sure that the path I use in the second code exists , and work , inRecordFile is the caf file name
NSError *error = nil;
NSString *documentFolderPath = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString *mainImageFolderPath=[documentFolderPath stringByAppendingPathComponent:#"Audio"];
if (![[NSFileManager defaultManager] fileExistsAtPath:mainImageFolderPath])
{
[[NSFileManager defaultManager] createDirectoryAtPath:mainImageFolderPath
withIntermediateDirectories:YES
attributes:nil
error:NULL];
}
NSDateFormatter *nameFormatter = [[NSDateFormatter alloc] init];
[nameFormatter setDateFormat:#"yyyyMMddHHmmss"];
NSString *nameString = [nameFormatter stringFromDate:[NSDate date]];
[nameFormatter release];
NSString *AudioPath = [mainImageFolderPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.caf",nameString]];
[[NSFileManager defaultManager] copyItemAtPath:[NSTemporaryDirectory() stringByAppendingPathComponent: #"recordedFile.caf"] toPath:AudioPath error:&error];
if(error)
NSLog(#"Error audio %#", [error description]);
else{
[self.notifier voiceAdded:AudioPath];
self.recordPath = AudioPath;
containsSound = YES;
}
Why are you going in more complexity? just when ur sound is recorded, copy caf file to your desired directory.

Creating zip files in ObjectiveC for 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];