Get document directory files date modified time in iphone - 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];

Related

Name of folder in my directory path in iPhone

I am new to iPhone,
I want to check how many folders are there in my Document Directory and i want fetch name of all folders and i want to store it in my array.
I want only name of folders and not contents inside folder.
Any help will be appreciated.
NSFileManager *mgr = [NSFileManager defaultManager];
NSString *documentsDir [NSSearchPathsForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSArray *allFilesInDocuments = [mgr contentsOfDirectoryAtPath:documentsDir error:NULL];
NSMutableArray *found = [NSMutableArray array];
for (NSString *filename in allFilesInDocuments)
{
NSString *fullPath = [documentsDir stringByAppendingPathComponent:filename];
BOOL isDir;
[mgr fileExistsAtPath:fullPath isDirectory:&isDir];
if (isDir) [found addObject:fullPath]; // or filename
}
now found should contain all the paths/names of the subdirectories of the Documents directory (i. e. entries in the Documents directory which are directories themselves.)
#define rootFileName XXXXXXXX
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *yourDirectory = [documentsDirectory stringByAppendingPathComponent:rootFileName];
//fileList便是包含有该文件夹下所有文件的文件名及文件夹名的数组
NSArray *fileList = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:yourDirectory error:nil];
for(int i = 0; i < [fileList count]; i++)
{
NSString *fileName = [fileList objectAtIndex:i];
NSLog(#"yourFileName:%#",fileName);
if([fileName isEqualToString:#".DS_Store"])
{
NSString *dotDS_StorePath = [NSString stringWithFormat:#"%#/.DS_Store",yourDirectory];
[[NSFileManager defaultManager] removeItemAtPath:dotDS_StorePath error:nil];
}
}
there is one thing you should know , the fileLists has a more file is .DS_Store , the file is created by the os.
DO this:
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *fileList = [[fileManager directoryContentsAtPath:yourDocumentPath] retain]; // your path here instead (DOCUMENTS_FOLDER)
NSMutableArray *directoryList = [[NSMutableArray alloc] init];
for(NSString *file in fileList) {
NSString *path = [yourDocumentPath stringByAppendingPathComponent:file]; // create path for directory and check it exits or not as directory
BOOL isDir = NO;
[fileManager fileExistsAtPath:path isDirectory:(&isDir)];
if(isDir) {
[directoryList addObject:file];
}
}
NSLog(#"%#", directoryList);
take a look at the NSFileManager class
it sounds like you want the subpathsAtPath: method
here's the sample code
BOOL isDir=NO;
NSArray *subpaths;
NSString *fontPath = #"/System/Library/Fonts";
NSFileManager *fileManager = [[NSFileManager alloc] init];
if ([fileManager fileExistsAtPath:fontPath isDirectory:&isDir] && isDir)
subpaths = [fileManager subpathsAtPath:fontPath];
[fileManager release];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory error:nil];
NSLog(#"files array %#", filePathsArray);
Simplest method:
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"])
{
NSLog(#"\n %#",imageName);
}
}

how do we open an already existing database fmdb and where to include it?

I am using fmdb but i am not knowing where to add the db file.
I found this old answer that i think it doesn't fit for xcode 4.2 (since we dont have 'Resources' folder anymore).
I created a database in 'Lita', added the extension .sqlite and added the db file as follows :
then tried to use the following
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsPath = [paths objectAtIndex:0];
NSString *path = [docsPath stringByAppendingPathComponent:#"db.sqlite"];
FMDatabase *database = [FMDatabase databaseWithPath:path];
[database open];
FMResultSet *results = [database executeQuery:#"select * from tbl"];
printf("hi");
while([results next]) {
printf("hi2");
NSString *name = [results stringForColumn:#"clm1"];
NSString *text = [results stringForColumn:#"clm2"];
NSLog(#"test: %# - %#",name, text);
}
printf("done");
i am getting the 'hi' 'done' but never 'hi2'...
anyone can help?
You want to add the (compiled) database to the project as a resource, and then copy it into the documents folder of the app on first start-up.
Here is an example method that does the work, call it from the applicationDidFinishLaunching and use the resultant FMDatabase * for all you queries.
- (FMDatabase *)openDatabase
{
NSFileManager *fm = [NSFileManager defaultManager];
NSString *documents_dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *db_path = [documents_dir stringByAppendingPathComponent:[NSString stringWithFormat:#"database.s3db"]];
NSString *template_path = [[NSBundle mainBundle] pathForResource:#"template_db" ofType:#"s3db"];
if (![fm fileExistsAtPath:db_path])
[fm copyItemAtPath:template_path toPath:db_path error:nil];
FMDatabase *db = [FMDatabase databaseWithPath:db_path];
if (![db open])
NSLog(#"Failed to open database!");
return db;
}
I am working with the same issues right now. But to answer your question: the documents folder is the folder that is to be used in the device.
Put the database in the the supporting files folder.
Here is what works for me:
//hide status bar for full screen view
[[UIApplication sharedApplication]setStatusBarHidden:YES withAnimation:UIStatusBarAnimationNone];
//set reference to database here
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDir = [documentPaths objectAtIndex:0];
self.databasePath = [documentDir stringByAppendingPathComponent:#"RPRA.sqlite"];
[self createAndCheckDatabase];
// Override point for customization after application launch.
return YES;
}
//method used to create database and check if it exists
-(void) createAndCheckDatabase
{
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
success = [fileManager fileExistsAtPath:self.databasePath];
if(success) return;
//else move database into documents folder
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath]
stringByAppendingPathComponent:#"RPRA.db"];
[fileManager copyItemAtPath:databasePathFromApp toPath:self.databasePath error:nil];
}
- (void)ensureDBFile
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dbFilePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"retails.sqlite"]];
NSLog(#"Database Filepath Delgate = %#", dbFilePath);
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL dbFileExists = [fileManager fileExistsAtPath:dbFilePath];
if(!dbFileExists){
//Copy the db file if it didn't exist
NSString *bundledDbPath = [[NSBundle mainBundle] pathForResource:#"retails" ofType:#"sqlite"];
if (bundledDbPath != nil) {
BOOL copiedDbFile = [fileManager copyItemAtPath:bundledDbPath toPath:dbFilePath error:nil];
if (!copiedDbFile) {
NSLog(#"Error: Couldn't copy the db file from the bundle");
}
}
else {
NSLog(#"Error: Couldn't find the db file in the bundle");
}
}
self.db = [FMDatabase databaseWithPath:dbFilePath];
[self.db setShouldCacheStatements:NO];
[self.db open];
if([self.db hadError]) {
NSLog(#"Database Error %d: %#", [self.db lastErrorCode], [self.db lastErrorMessage]);
}
}

Create and save NSString data in to a file

i have 3NSString objects that i want to save to a new file when the app is running.
this will help me for remote debug!
if any one can help me creating the file and save the data to it will be very use full
thanx
You can save the files to the Documents directory, here is how to get the path to that directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];
And a sample write statement:
NSError *error;
BOOL status = [string writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
In the NSString documentation there is method called writeToFile:atomically:encoding:error:.
NSError *error;
[#"Write me to file" writeToFile:#"<filepath>" atomically:YES encoding: NSUTF8StringEncoding error:&error];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents directory
NSError *error; BOOL succeed = [myString writeToFile:[documentsDirectory stringByAppendingPathComponent:#"myfile.txt"]
atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (!succeed){
// Handle error here }
source.
Here is how to save NSString into Documents folder. Saving other types of data can be also realized that way.
- (void)saveString:(NSString *)stringToSave toDocumentsWithFilename:(NSString *)fileName {
NSString *documentsFolder = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString *path = [documentsFolder stringByAppendingPathComponent:fileName];
[[NSFileManager defaultManager] createFileAtPath:path contents:[stringToSave dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];
}
Usage:
NSString *stringWeWantToSave = #"This is an elephant";
NSString *fileName = [NSString stringWithString:#"savedString.txt"];
[self saveString:stringWeWantToSave toDocumentsWithFilename:fileName];

how to append tags in xml in iphone?

i am new developer in iphone application. i would like write a content in xml file for that, i have created xml file and write tags with element, attribute and value with some data in that xml as follows.
-(void)writexmlfile:(NSString *)data toFile:(NSString *)fileName NodeName:(NSString *)Node{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// the path to write file
NSString *fileExtension = [NSString stringWithFormat:#"%#%#",fileName,#".xml"];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileExtension];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:appFile];
if(fileExists) {
NSError *error = nil;
NSString *docStr;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// the path to write file
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileName];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:appFile];
if(fileExists)
{
NSLog(#"file exist in document");
NSData *myData1 = [NSData dataWithContentsOfFile:appFile];
if (myData1) {
docStr = [[NSString alloc] initWithData:myData1 encoding:NSASCIIStringEncoding];
XMLString = [[NSMutableString alloc]initWithString:docStr];
[self XMLString];
NSLog(#"data%#",XMLString);
}
}
// [XMLString insertString:data atIndex:index];
[XMLString appendFormat:#"<%#>%#</%#> \n",Node,data,Node];
BOOL success = [XMLString writeToFile:appFile atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (!success) {
NSLog(#"Error: %#", [error userInfo]);
}
else {
NSLog(#"File write is successful");
}
}
}
i want add new tag with new elements,new attributes,etc.,if i enter element at the place of tag it is modifying with previous tag .
here how can i append the new tag to previous appended tags
please any body could help me
Thanks in advance
As a suggestion, you can use APXML to create XML documents it is very simple and easy to use. This post can guide you further.

remove images from NSHomeDirectory() in iphone

Hi i am saving images like this:
[UIImagePNGRepresentation(image) writeToFile:[self findUniqueSavePath] atomically:YES];
// Show the current contents of the documents folder
CFShow([[NSFileManager defaultManager] directoryContentsAtPath:[NSHomeDirectory() stringByAppendingString:#"/Documents"]]);
- (NSString *) findUniqueSavePath
{
int i = 1;
NSString *path;
do
{
// iterate until a name does not match an existing file
path = [NSString stringWithFormat:#"%#/Documents/IMAGE-%d.PNG", NSHomeDirectory(), i++];
} while ([[NSFileManager defaultManager] fileExistsAtPath:path]);
[classObj updateimage];
return path;
}
I want to remove images when the new image write in the document.
you can use this code
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path=[documentsDirectory stringByAppendingPathComponent:#"image.png"];
[[NSFileManager defaultManager] removeItemAtPath:path error:nil];