I have a list of image in Document folder of app.And I want to load images in order of date created.
How can I do that ?
This code will enumerate all files in your documents directory in the order they were created:
See comments in the code to understand what is going on.
NSFileManager *fm = [NSFileManager defaultManager];
NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSError *err;
// Get all files with their creation date
NSArray *files = [fm contentsOfDirectoryAtURL:[[NSURL alloc] initFileURLWithPath:doc isDirectory:YES]
includingPropertiesForKeys:[NSArray arrayWithObject:NSURLCreationDateKey]
options:0
error:&err];
// Using file's URL as the key, store creation date as the value
NSMutableDictionary *urlWithDate = [NSMutableDictionary dictionaryWithCapacity:files.count];
for (NSURL *f in files) {
NSDate *creationDate;
if ([f getResourceValue:&creationDate forKey:NSURLCreationDateKey error:&err]) {
[urlWithDate setObject:creationDate forKey:f];
}
}
// Sort the dictionary on the value, which is the creation key
for (NSURL *f in [urlWithDate keysSortedByValueUsingComparator:^NSComparisonResult(id obj1, id obj2) {
return [obj1 compare:obj2];
}]) {
// Check if the file is an image. Load if it is an image, otherwise skip.
NSLog(#"%#", f);
}
I would take a look: Getting a list of files in a directory with a glob
Specifically the NSFileManager. You can look at attributes of the file. From there you can most likely do a sort using NSPredicate.
Related
I have a Settings.plist and I want to edit some values in this file.
My function to edit/writing is:
- (void) setParamWithName: (NSString*) Name withValue: (NSString*) Value {
// get paths from root direcory
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
// get documents path
NSString *documentsPath = [paths objectAtIndex:0];
// get the path to plist file
NSString *plistPath = [documentsPath stringByAppendingPathComponent:#"Settings.plist"];
// check to see if Data.plist exists in documents
if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath])
{
// if not in documents, get property list from main bundle
plistPath = [[NSBundle mainBundle] pathForResource:#"Settings" ofType:#"plist"];
}
// read property list into memory as an NSData object
NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath];
NSString *errorDesc = nil;
NSPropertyListFormat format;
// convert static property list into dictionary object
NSDictionary *temp = (NSDictionary *)[NSPropertyListSerialization propertyListFromData:plistXML mutabilityOption:NSPropertyListMutableContainersAndLeaves format:&format errorDescription:&errorDesc];
if (!temp)
{
NSLog(#"Error reading plist: %#, format: %d", errorDesc, format);
}
// checking if element exists, if yes overwriting
// if element not exists adding new element
[temp writeToFile:plistPath atomically:YES];
}
This function read and write (with te same values) Settings.plist.
I do not have any idea (my knowledge about objective-c is not enough) how to add new element or edit existing element. Can anyone help mi with this issue?
I think it's easier as you think.
Once you got the path of the file read it into a NSDictionary. Make a mutable copy of that dictionary with mutableCopy and NSMutableDictionary.
Now edit that mutable dictionary as you like (add s.th., remove s.th., edit s.th. and so on).
Now that you're done you can write it back to the old path as you did with temp.
Your main problem is that you're not working with a mutable version of that dicitionary. It'd make your life much easier.
Program that Creates multiple Plist's Paths for Different information.
But only one path is not working.
(i think "writeToFile" is the problem)
code:
-(NSString *) createPath:(NSString *)withFileName
{
NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,
YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:withFileName];
return path;
}
Path
NSLog = /var/mobile/Applications/02CABC0A-6B5B-4097-A9D1-4336BE8230B7/Documents/MessagesDB.plist
&
-(void) messagesDbFlush
{
// save it to the file for persistency
NSString *messagesDB_Path = [self createPath:_fileMessagesDB];
[_messagesDB writeToFile:messagesDB_Path atomically:YES];
NSMutableArray *ReturnsInfo = [[NSMutableArray alloc ]initWithContentsOfFile:messagesDB_Path];
NSLog(#"ReturnsInfo is : %#", ReturnsInfo);
}
"ReturnsInfo" Array is Null :/
Anyone please help?
I once had the same error.
1) Check the name of the plist in the directory listing to match your coded one
2) Check Project settings, manually delete the pre-existing plist from the "Build Settings" > "Copy Bundle Resources", and drag drop from the list.
3) Select the plist in directory listing, check Utilities sidebar, check Identity & Type > Location as valid
4) If you deleted the app's "default" plist aka bundle identifier, add copy build phase, choose destination, choose pref folder as absolut path check "copy only when installing"
This solved my returning null.
And if all fails on the bundle identifier, you can always copy the plist to pref folder by code:
NSString *path = [#"~/Library/Preferences/com.MyCompany.MyApp.plist" stringByExpandingTildeInPath];
BOOL PrefsExist=[[NSFileManager defaultManager] fileExistsAtPath:path];
NSString *copyPrefsPath = [#"~/Library/Preferences/com.MyCompany.MyApp.plist" stringByExpandingTildeInPath];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (PrefsExist == 0)
{
// Copy the plist to prefs folder (one-time event)
NSString *tessdataPath = [[NSBundle mainBundle] pathForResource:#"com.MyCompany.MyApp" ofType:#"plist"];
[fileManager copyItemAtPath:tessdataPath toPath:path error:&error];
} else
{
// Read/Write the values from plist
}
i have stored following array with 5 objects in it, its working fine on my side, try it
NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:5];
for(int i=0;i<5;i++)
[array addObject:#"This is Demo String, You can write your own String here"];
NSString *_fileMessagesDB = #"MessagesDB.plist";
// save it to the file for persistency
NSString *messagesDB_Path = [self createPath:_fileMessagesDB];
[array writeToFile:messagesDB_Path atomically:YES];
NSMutableArray *ReturnsInfo = [[NSMutableArray alloc ]initWithContentsOfFile:messagesDB_Path];
NSLog(#"ReturnsInfo is : %#", ReturnsInfo);
I am looking for a simple way in Objective-C to select all of the .jpg files in a directory. Right now I can only get all of the directory contents. Is there a way to apply a wildcard, like *.jpg, to the results?
if ( [[NSFileManager defaultManager] isReadableFileAtPath:#"/folder2/"] )
[[NSFileManager defaultManager] copyItemAtPath:#"/folder2/" toPath:#"/folder1/" error:nil];
You could use something like:
NSArray *list = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:#"/folder2/" error:nil];
for (NSString* file in list) {
if ([[file pathExtension] isEqualToString: #"jpg"]) {
[[NSFileManager defaultManager] copyItemAtPath:file toPath:#"/folder1/" error:nil];
}
}
The contentsOfDirectoryAtPath:error method returns an array containing the names of the files in the specified directory. For each entry, the result of the NSString pathExtension method is compared against the target string ("jpg"). Any matching files are copied into the destination directory.
Pretty much straight from the docs:
NSDirectoryEnumerator *dirEnum = [localFileManager enumeratorAtPath:docsDir];
NSString *file;
while (file = [dirEnum nextObject]) {
if ([[file pathExtension] isEqualToString: #"jpg"]) {
// process the document
[self doSomethingWithFile: [docsDir stringByAppendingPathComponent:file]];
}
}
It looks like NSDirectoryEnumerator also supports fast enumeration, so you could use that instead:
NSDirectoryEnumerator *dirEnum = [localFileManager enumeratorAtPath:docsDir];
for (NSString *file in dirEnum) {
if ([[file pathExtension] isEqualToString: #"doc"]) {
// process the document
[self doSomethingWithFile: [docsDir stringByAppendingPathComponent:file]];
}
}
The difference between using a directory enumerator and iterating over the list returned by -contentsOfDirectoryAtPath: is that the directory enumerator will also provide results from subdirectories.
I already get path for documents directory and create some directories inside. I already know how to check if directory exist, delete it or its files but, how could I list directories? Thank you.
for file listing I use:
int Count;
NSString *path;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
path = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"SomeDirectoryName"];
NSArray *directoryContent = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:NULL];
for (Count = 0; Count < (int)[directoryContent count]; Count++)
{
NSLog(#"File %d: %#", (Count + 1), [directoryContent objectAtIndex:Count]);
}
For example, this method removes all files from temporary directory of application:
- (void)cleatTmpDirectory
{
// Create a local file manager instance
NSFileManager *localFileManager = [[NSFileManager alloc] init];
NSURL *directoryToScan = [NSURL fileURLWithPath:[self applicationTmpDirectory]];
NSDirectoryEnumerator *dirEnumerator =
[[localFileManager enumeratorAtURL:directoryToScan
includingPropertiesForKeys:[NSArray arrayWithObjects:NSURLIsDirectoryKey,nil]
options: NSDirectoryEnumerationSkipsHiddenFiles |
NSDirectoryEnumerationSkipsSubdirectoryDescendants |
NSDirectoryEnumerationSkipsPackageDescendants
errorHandler:nil] retain];
NSError *error;
// Enumerate the dirEnumerator results, each value is stored in allURLs
for (NSURL *theURL in dirEnumerator)
{
// Retrieve whether a directory.
NSNumber *isDirectory;
[theURL getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:NULL];
if ([isDirectory boolValue] == NO)
{
[localFileManager removeItemAtURL:theURL error:&error];
}
}
// Release the localFileManager.
[localFileManager release];
}
As you can find you should use NSDirectoryEnumerator *dirEnumerator and pass to its initialization method appropriate keys that you will then use.
Use the NSDirectoryEnumerator returned by NSFileManager's -enumeratorAtPath: method.
I have been trying to create a new file inside of my application support folder while using NSApplicationSupportDirectory; I can write a file to it, but I have been unable to create a folder inside of Application Support.
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *applicationDirectory = [paths objectAtIndex:0];
//make a file name to write the data to using the application support: (attempting to create the blasted directory inside of application support directory
NSString *fileName = [NSString stringWithFormat:#"%#/managersemail.txt",
applicationDirectory];
//create content - formats with the managersemail.txt location
NSString* content = [NSString stringWithFormat:#"%#",[nameField stringValue]];
//save content to the documents directory
[content writeToFile:fileName
atomically:NO
encoding:NSStringEncodingConversionAllowLossy
error:nil];
NSDictionary* errorDict;
The code that I have listed above works great, except for the part about creating the folder in which I want to place the managersemail.txt. I tried to mimic the stringWithFormat that is listed in the NSString* content and then varying several ways however to no avail! Any thoughts?
NSAppleEventDescriptor* returnDescriptor = NULL;
Perhaps the solution provided on Cocoa with Love might be useful?
Excerpt:
- (NSString *)findOrCreateDirectory:(NSSearchPathDirectory)searchPathDirectory
inDomain:(NSSearchPathDomainMask)domainMask
appendPathComponent:(NSString *)appendComponent
error:(NSError **)errorOut
{
// Search for the path
NSArray* paths = NSSearchPathForDirectoriesInDomains(
searchPathDirectory,
domainMask,
YES);
if ([paths count] == 0)
{
// *** creation and return of error object omitted for space
return nil;
}
// Normally only need the first path
NSString *resolvedPath = [paths objectAtIndex:0];
if (appendComponent)
{
resolvedPath = [resolvedPath
stringByAppendingPathComponent:appendComponent];
}
// Check if the path exists
BOOL exists;
BOOL isDirectory;
exists = [self
fileExistsAtPath:resolvedPath
isDirectory:&isDirectory];
if (!exists || !isDirectory)
{
if (exists)
{
// *** creation and return of error object omitted for space
return nil;
}
// Create the path if it doesn't exist
NSError *error;
BOOL success = [self
createDirectoryAtPath:resolvedPath
withIntermediateDirectories:YES
attributes:nil
error:&error];
if (!success)
{
if (errorOut)
{
*errorOut = error;
}
return nil;
}
}
if (errorOut)
{
*errorOut = nil;
}
return resolvedPath;
}
Maybe you can try using the NSFileManager to create the folder, then write the file into the folder.
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *applicationSupport = [[NSString stringWithString:#"~/Library/Application Support/'YOUR APP'] stringByExpandingTildeInPath];
if ([fileManager fileExistsAtPath:applicationSupport] == NO)
[fileManager createDirectoryAtPath:applicationSupport withIntermediateDirectories:YES attributes:nil error:nil];
NSString *fileName = [NSString stringWithFormat:#"%#/managersemail.txt", applicationSupport];
NSString* content = [NSString stringWithFormat:#"%#",[nameField stringValue]];
//save content to the documents directory
[content writeToFile:fileName
atomically:NO
encoding:NSStringEncodingConversionAllowLossy
error:nil];
So something like that should work. Feel free to leave comments to ask questions.