How to remove a directory and its contents using NSFileManager - iphone

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.

Related

renaming and saving in NSDocumentsDirectory

Its like this, in my app, I have a UIScrollView on it is a thumbnail view, they are images from my NSCachesDirectory.
I saved them from my picker then named them in my array like: images0.png,images.1.png... etc
So for example I have images in my directory this way : images0.png, images1.png, images2.png, images3.png.
Then I delete images1.png, the remaining images will be like this : images0.png,images2.png, images3.png right?
What I wanted to achieve is get the images in NSDocumentsDirectory then renamed them AGAIN or sort them again like images0.png, images1.png, images2.png...etc again?
is this possible? hope you could help me.
Use this NSFileManger moveItemAtPath: toPath: error: but you should supply the toPath:same_path_but_different_filename. This moves the file to a new path with new file name that you provide. see this
Since it seems you want the whole logic to rename your images file, here is the code you can try provided the files are in the Document directory
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString * oldPath =[[NSString alloc]init];
NSString * newPath =[[NSString alloc]init];
int count=0;
for (int i=0; i<=[[fileManager contentsOfDirectoryAtPath:documentsDirectory error:nil]count]; i++) {
oldPath=[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"images%d.png",i]];
if ([fileManager fileExistsAtPath:oldPath]) {
newPath=[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"images%d.png",count]];
[fileManager moveItemAtPath:oldPath toPath:newPath error:nil];
count+=1;
}
}
Apple doesnot allow renameing of file saved. So alternative is to get all contents at document directory like this:
NSArray *directoryContent = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:yourDocDirPath error:NULL];
Now sort like this:
NSSortDescriptor * descriptor = [NSSortDescriptor sortDescriptorWithKey:nil ascending: YES comparator:^NSComparisonResult(id obj1, id obj2){
return [obj1 compare: obj2 options: NSNumericSearch];
}];
NSArray * sortedDirectoryContent = [directoryContent sortedArrayUsingDescriptors:[NSArray arrayWithObject: descriptor]];
We have sorted array rewrite all files with new name:
for(NSString *fileName in sortedDirectoryContent)
{
NSString *filePath = [yourDocDirPath stringByAppendingPathComponent:fileName];
NSData *fileData = [[NSData alloc]initWithContentsOfFile:filePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
[[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
if(fileData)
{
NSString *newFilePath = [yourDocDirPath stringByAppendingPathComponent:#"New Name here"];
[fileData writeToFile:newFilePath atomically:YES];
}
}
else
{
if(fileData)
{
NSString *newFilePath = [yourDocDirPath stringByAppendingPathComponent:#"New Name here"];
[fileData writeToFile:newFilePath atomically:YES];
}
}
}

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 to check if a directory exists in Objective-C

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];

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

NSFileManager in document folder

i am trying to zip a file into a subfolder in my iphone app.
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *dir = [path objectAtIndex:0];
NSString *storeunzipfiles = [dir stringByAppendingPathComponent:#"/MyFolder"];
if (![[NSFileManager defaultManager] fileExistsAtPath:storeunzipfiles])
[[NSFileManager defaultManager] createDirectoryAtPath:storeunzipfiles attributes:nil]; //Create folder
ok now i created the folder. What i want to do is to del all the files in the folder before i unzip my file. but i am not getting it.
NSFileManager *filemgr;
filemgr = [NSFileManager defaultManager];
[filemgr removeItemAtPath: #"/MyFolder" handler: nil];
// warning: 'NSFileManager' may not respond to '-removeItemAtPath:handler:'
}
}
lastly, unzip to subfolder.
if ([zip UnzipFileTo:storeunzipfiles overWrite:YES]) {...
ok i got a warning msg...
whats the method to load the files in the subfolder? is this right?
NSString *docpath = [documentsDirectory stringByAppendingPathComponent:#"/MyFolder/Data.plist"]; ?
thks in advance
There is no -removeItemAtPath:handler: method. You want -removeItemAtPath:error: instead.
No,
You can use method
- (NSArray *)contentsOfDirectoryAtPath:(NSString *)path error:(NSError **)error
this will return a NSarray object that contains Name of File contains in given folder.
after that u can remove easily. example
NSarray *array=[filemanager contentsOfDirectoryAtPath:#"/MyFolder" error:nil];
for(int i=0;i<[array count];i++)
{
[filemanager removeItemAtPath:[#"/MyFolder" stringByAppendingPathComponent:[array objectAtIndex:i]] error:nil];
}
so folder will be empty