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.
Related
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.
}
}
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];
I have generated a property list which save some hospital names. Now I want to get the names into an array from that plist. please help me. Thanx in advance.
NSString* plistPath = [[NSBundle mainBundle] pathForResource:#"sample" ofType:#"plist"];
contentArray = [NSArray arrayWithContentsOfFile:plistPath];
try this
Try this
NSMutableDictionary* dictionary = [[[NSMutableDictionary alloc] init] autorelease];
NSError *error;
// Look in Documents for an existing plist file
NSArray *paths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* metadataPlistPath = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat: #"Metadata.plist"]];
[metadataPlistPath retain];
// If it's not there, copy it from the bundle
NSFileManager *fileManger = [NSFileManager defaultManager];
if ( ![fileManger fileExistsAtPath:metadataPlistPath] ) {
NSString *pathToSettingsInBundle = [[NSBundle mainBundle]
pathForResource:#"Metadata" ofType:#"plist"];
[fileManger copyItemAtPath:pathToSettingsInBundle toPath:metadataPlistPath error:&error];
}
//Now read the plist file from Documents
NSString* myPlistPath = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat: #"Metadata.plist"] ];
dictionary = [[NSMutableDictionary alloc] initWithContentsOfFile:myPlistPath];
return dictionary;
}
//fetch the data based on key
- (NSMutableArray*) fetchMetadataArrayForKey:(NSString*)aKey {
NSMutableArray* arrCategories = [[[NSMutableArray alloc] init] autorelease];
NSMutableDictionary* dictionary = [self fetchMetadata];
arrCategories = [dictionary valueForKey:aKey];
return arrCategories;
}
+ (void)findAndCopyOfDatabaseIfNeeded{
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [path objectAtIndex:0];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *databasePath = [documentsDirectory stringByAppendingPathComponent:#"DB"];
BOOL success = [fileManager fileExistsAtPath:databasePath];
if(!success){
NSString *resourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"DB"];
[fileManager copyItemAtPath:resourcePath toPath:databasePath error:NULL];
}
NSString *tracePath = [documentsDirectory stringByAppendingPathComponent:#"Trace"];
BOOL traceDir = [fileManager fileExistsAtPath:tracePath];
if(!traceDir){
NSString *resourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"Trace"];
[fileManager copyItemAtPath:resourcePath toPath:tracePath error:NULL];
}
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"yyyy"];
NSDate *today = [[NSDate alloc]init];
NSString *resultYear = [dateFormatter stringFromDate:today];
NSString *traceYearPath = [tracePath stringByAppendingPathComponent:resultYear];
BOOL yearDir = [fileManager fileExistsAtPath:tracePath];
if (!yearDir) {
[fileManager createDirectoryAtPath:traceYearPath attributes:nil];
}
//[resultYear release]; ?
//[today release]; ?
//[dateFormatter release]; ?
}
I'm using global class like this [ + (void)findAndCopyOfDatabaseIfNeeded ].
hm,, I don't know NSArray, NSString and NSFileManager are released.
Variable release or Not release ? please advice for me.
NSString *resultYear = [dateFormatter stringFromDate:today];
//[resultYear release]; ?
You do not need to release resultYear. The object returned from the stringFromDate: will be autorelease'd.
It's usually safe to assume that objects returned from methods whose names do not start with "create" or "new" will be autorelease'd. At least with Apple code, but this is a convention for Cocoa in general, so you should also follow it.
NSDate *today = [[NSDate alloc]init];
//[today release]; ?
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
//[dateFormatter release]; ?
You need to release both today and dateFormatter, since you alloc'ed them. Always pair an alloc with a release or autorelease in your own code.
yes, and some more:
do not release NSArray * path - it is autoreleased (almost always id returned by functions are).
also do not release fileManager - it is shared singleton object
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];