How to check if a directory exists in Objective-C - iphone

I guess this is a beginner's problem, but I was trying to check if a directory exists in my Documents folder on the iPhone. I read the documentation and came up with this code which unfortunately crashed with EXC_BAD_ACCESS in the BOOL fileExists line:
-(void)checkIfDirectoryAlreadyExists:(NSString *)name
{
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSString *path = [[self documentsDirectory] stringByAppendingPathComponent:name];
BOOL fileExists = [fileManager fileExistsAtPath:path isDirectory:YES];
if (fileExists)
{
NSLog(#"Folder already exists...");
}
}
I don't understand what I've done wrong? It looks all perfect to me and it certainly complies with the docs, not? Any revelations as to where I went wrong would be highly appreciated! Thanks.
UPDATED:
Still not working...
-(void)checkIfDirectoryAlreadyExists:(NSString *)name
{
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSString *path = [[self documentsDirectory] stringByAppendingPathComponent:name];
BOOL isDir;
BOOL fileExists = [fileManager fileExistsAtPath:path isDirectory:&isDir];
if (fileExists)
{
if (isDir) {
NSLog(#"Folder already exists...");
}
}
}

Take a look in the documentation for this method signature:
- (BOOL)fileExistsAtPath:(NSString *)path isDirectory:(BOOL *)isDirectory
You need a pointer to a BOOL var as argument, not a BOOL itself. NSFileManager will record if the file is a directory or not in that variable. For example:
BOOL isDir;
BOOL exists = [fm fileExistsAtPath:path isDirectory:&isDir];
if (exists) {
/* file exists */
if (isDir) {
/* file is a directory */
}
}

Just in case somebody needs a getter, that creates a folder in Documents, if it doesn't exist:
- (NSString *)folderPath
{
if (! _folderPath) {
NSString *folderName = #"YourFolderName";
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [documentPaths objectAtIndex:0];
_folderPath = [documentsDirectoryPath stringByAppendingPathComponent:folderName];
// if folder doesn't exist, create it
NSError *error = nil;
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL isDir;
if (! [fileManager fileExistsAtPath:_folderPath isDirectory:&isDir]) {
BOOL success = [fileManager createDirectoryAtPath:_folderPath withIntermediateDirectories:NO attributes:nil error:&error];
if (!success || error) {
NSLog(#"Error: %#", [error localizedDescription]);
}
NSAssert(success, #"Failed to create folder at path:%#", _folderPath);
}
}
return _folderPath;
}

I have a Utility singleton class that I use for things like this. Since I can’t update my database if it remains in Documents, I copy my .sqlite files from Documents to /Library/Private Documents using this code. The first method finds the Library. The second creates the Private Documents folder if it doesn’t exist and returns the location as a string. The second method uses the same file manager method that #wzboson used.
+ (NSString *)applicationLibraryDirectory {
return [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
}
+ (NSString *)applicationLibraryPrivateDocumentsDirectory {
NSError *error;
NSString *PrivateDocumentsDirectory = [[self applicationLibraryDirectory] stringByAppendingPathComponent:#"Private Documents"];
BOOL isDir;
if (! [[NSFileManager defaultManager] fileExistsAtPath:PrivateDocumentsDirectory isDirectory:&isDir]) {
if (![[NSFileManager defaultManager] createDirectoryAtPath:PrivateDocumentsDirectory
withIntermediateDirectories:NO
attributes:nil
error:&error]) {
NSLog(#"Create directory error: %#", error);
}
}
return PrivateDocumentsDirectory;
}
I use it like this in my persistent store coordinator initialization. The same principal applies to any files though.
NSString *libraryDirectory = [Utilities applicationLibraryPrivateDocumentsDirectory];
NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:sqliteName];
NSString *destinationPath = [libraryDirectory stringByAppendingPathComponent:sqliteName];

Related

How to remove Temporary Directory files fron iOS app?

i used code for remove Temporary Directory files when using device.
-(void) clearAllTempFiles {
NSString *path = NSTemporaryDirectory();
if ([path length] > 0)
{
NSError *error = nil;
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL deleted = [fileManager removeItemAtPath:path error:&error];
if (deleted != YES || error != nil)
{
}
else{
// Recreate the Documents directory
[fileManager createDirectoryAtPath:path withIntermediateDirectories:NO attributes:nil error:&error];
}
}
}
it's not working fine? this is right code for deleting files from Temporary Directory?
pls help me?
You can get the tmp directory name on your mac by using this in your code:
Code:
(void)cacheDirectory {
NSString *tempPath = NSTemporaryDirectory();
NSLog(#"Temp Value = %#", items);
}
Call the method from wherever you want.
This will return the tmp folder name, then in finder do (cmd-shift-G) and paste the response you got from the console window.
The following will clear the TMP directory used by the Simulator.
Code:
NSString *tempPath = NSTemporaryDirectory();
NSArray *dirContents = [[NSFileManager defaultManager] directoryContentsAtPath:tempPath];
NSArray *onlyJPGs = [dirContents filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"self ENDSWITH '.jpg'"]];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (onlyJPGs) {
for (int i = 0; i < [onlyJPGs count]; i++) {
NSLog(#"Directory Count: %i", [onlyJPGs count]);
NSString *contentsOnly = [NSString stringWithFormat:#"%#%#", tempPath, [onlyJPGs objectAtIndex:i]];
[fileManager removeItemAtPath:contentsOnly error:nil];
}
The above code clears only JPGs from the directory, so if you want to clear anything else then amend it.
I found simple one
NSArray* tmpDirectory = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:NSTemporaryDirectory() error:NULL];
for (NSString *file in tmpDirectory) {
[[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:#"%#%#", NSTemporaryDirectory(), file] error:NULL];
}

How get list of folders and files from resource folder in iPhone?

I am doing folder structure in my resource folder like... Resource => MyData => S1
then in S1=> Name.png, data.ppt
Now I want to get all folder list and file names. Here MyData name will be only static other may change.Like I can add S1, S2 , S3 and number of files in that. So how to read these contents through Objective C? I tried below code.
NSString *bundlePathName = [[NSBundle mainBundle] bundlePath];
NSString *dataPathName = [bundlePathName stringByAppendingPathComponent:#"Resources"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:dataPathName]) {
NSLog(#"%# exists", dataPathName);
BOOL isDir = NO;
[fileManager fileExistsAtPath:dataPathName isDirectory:(&isDir)];
if (isDir == YES) {
NSLog(#"%# is a directory", dataPathName);
NSArray *contents;
contents = [fileManager contentsOfDirectoryAtPath:dataPathName error:nil];
for (NSString *entity in contents) {
NSLog(#"%# is within", entity);
}
} else {
NSLog(#"%# is not a directory", dataPathName);
}
} else {
NSLog(#"%# does not exist", dataPathName);
}
Thanks,
You can get the path to the Resources directory like this,
NSString * resourcePath = [[NSBundle mainBundle] resourcePath];
Then append the Documents to the path,
NSString * documentsPath = [resourcePath stringByAppendingPathComponent:#"Documents"];
Then you can use any of the directory listing APIs of NSFileManager.
NSError * error;
NSArray * directoryContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsPath error:&error];

How can i upload a UIImage to a specific folder in Documents?

I have a image name (lets say #"image.jpg" ) and i would like to save it to a folder i have created in my Documents folder named "coffeeShops". How can i do so ?
NSString *docs = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) objectAtIndex:0];
NSString *dir = #"coffeeShops";
NSString *destPath = [docs stringByAppendingPathComponent:dir];
// check if the destination directory exists, if not create it
BOOL isDirectory;
BOOL exists = [[NSFileManager defaultManager] fileExistsAtPath:destPath isDirectory:&isDirectory];
if(!exists || !isDirectory) {
NSError *error = nil;
[[NSFileManager defaultManager] createDirectoryAtPath:destPath withIntermediateDirectories:NO attributes:nil error:&error];
if(error != nil) {
// should do error checking here
NSLog(#"%#",[error localizedDescription]);
}
}
NSString *fileName = #"image.jpg";
NSString *path = [destPath stringByAppendingPathComponent:fileName];
[UIImageJPEGRepresentation(image) writeToFile:path atomically:YES];

Delete all files and folder from a certain folder

I have a /Documents/Images folder , in that folder are several other folders named after years , in those folders i have images. I want to delete everything from the images folder ( including the folders and the images in these folders).
I tried several code snippets but none delete the folders
my method:
- (void) clearCache:(NSString *) folderName{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSFileManager *fm = [NSFileManager defaultManager];
NSString *directory = [documentsDirectoryPath stringByAppendingPathComponent:folderName];
NSLog(#"Removing items at path: %#",directory);
NSError *error = nil;
BOOL succes = [fm removeItemAtPath:directory error:&error];
/*for (NSString *file in [fm contentsOfDirectoryAtPath:directory error:&error]) {
//BOOL success = [fm removeItemAtPath:[NSString stringWithFormat:#"%#%#", directory, file] error:&error];
BOOL success = [fm removeItemAtPath:[directory stringByAppendingPathComponent:file] error:&error];
if (!success || error) {
// it failed.
}
}*/
}
NSFileManager *fm = [NSFileManager defaultManager];
NSString *directory = [[self documentsDirectory] stringByAppendingPathComponent:#"urDirectory/"];
NSError *error = nil;
for (NSString *file in [fm contentsOfDirectoryAtPath:directory error:&error]) {
BOOL success = [fm removeItemAtPath:[NSString stringWithFormat:#"%#%#", directory, file] error:&error];
if (!success || error) {
// it failed.
}
}
Hope this helps
Your code ([fm removeItemAtPath:directory error:&error];) should do it. If it doesn't, inspect the error it returns. If there's no error, but you still see files/subfolders - file a bug report!
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSFileManager_Class/Reference/Reference.html

How to remove a directory and its contents using NSFileManager

New to Objective C. I have created a few directories which contain pdf files for an iPhone app. How can I delete a directory and its contents using NSFileManager?
Do I need to loop through and remove the contents first? Any code samples would be much appreciated.
Thanks in advance.
To start off, it would be wise to look through Apple's NSFileManager documentation for the iPhone: NSFileManager Class Reference. Second, look at NSFileManager's -removeItemAtPath:error: method and its documentation. That's what you're looking for.
Heres some code I use that Ive edited to suit the question
- (NSMutableString*)getUserDocumentDir {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSMutableString *path = [NSMutableString stringWithString:[paths objectAtIndex:0]];
return path;
}
- (BOOL) createMyDocsDirectory
{
NSMutableString *path = [self getUserDocumentDir];
[path appendString:#"/MyDocs"];
NSLog(#"createpath:%#",path);
return [[NSFileManager defaultManager] createDirectoryAtPath:path
withIntermediateDirectories:NO
attributes:nil
error:NULL];
}
- (BOOL) deleteMyDocsDirectory
{
NSMutableString *path = [self getUserDocumentDir];
[path appendString:#"/MyDocs"];
return [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
}
You can get document directory by using this:
NSString *directoryPath = [NSHomeDirectory() stringByAppendingString:#"/Documents/"];
** Remove full directory path by using this:
BOOL success = [fileManager removeItemAtPath:directoryPath error:nil];
if (!success) {
NSLog(#"Directory delete failed");
}
** Remove the contents of that directory using this:
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:directoryPath]) {
NSDirectoryEnumerator *dirEnum = [fileManager enumeratorAtPath:directoryPath];
NSString *documentsName;
while (documentsName = [dirEnum nextObject]) {
NSString *filePath = [directoryPath stringByAppendingString:documentsName];
BOOL isFileDeleted = [fileManager removeItemAtPath:filePath error:nil];
if(isFileDeleted == NO) {
NSLog(#"All Contents not removed");
break;
}
}
NSLog(#"All Contents Removed");
}
** You can edit directoryPath as per your requirement.