How to remove Temporary Directory files fron iOS app? - iphone

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

Related

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

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 rename directories?

I have created a folder within the Documents folder in my application directory .
I wanted to rename that folder through code,but not able to understand how to do it.
Please help me out.
Have you tried?
NString *newDirectoryName = #"<new folder name>";
NSString *oldPath = #"<path to the old folder>";
NSString *newPath = [[oldPath stringByDeletingLastPathComponent] stringByAppendingPathComponent:newDirectoryName];
NSError *error = nil;
[[NSFileManager defaultManager] moveItemAtPath:oldPath toPath:newPath error:&error];
if (error) {
NSLog(#"%#",error.localizedDescription);
// handle error
}
NSString *oldDirectoryPath = #"Type your old directory Path";
NSArray *tempArrayForContentsOfDirectory =[[NSFileManager defaultManager] contentsOfDirectoryAtPath:oldDirectoryPath error:nil];
NSString *newDirectoryPath = [[oldDirectoryPath stringByDeletingLastPathComponent]stringByAppendingPathComponent:newDirectoryname];
[[NSFileManager defaultManager] createDirectoryAtPath:newDirectoryPath attributes:nil];
for (int i = 0; i < [tempArrayForContentsOfDirectory count]; i++)
{
NSString *newFilePath = [newDirectoryPath stringByAppendingPathComponent:[tempArrayForContentsOfDirectory objectAtIndex:i]];
NSString *oldFilePath = [oldDirectoryPath stringByAppendingPathComponent:[tempArrayForContentsOfDirectory objectAtIndex:i]];
NSError *error = nil;
[[NSFileManager defaultManager] moveItemAtPath:oldFilePath toPath:newFilePath error:&error];
if (error) {
// handle error
}
}
Using moveItemAtPath should work. Sometimes the directory isn't actually "renamed" but really moved to another place. In which case the target path directory structure needs to be created as well.
Here a code snippet i'm using that works well :
-(BOOL)renameDir:(NSString *)dirPath asDir:(NSString *)newDirPath cleanExisting:(BOOL)clean
{
NSError *error = nil;
NSFileManager *fm = [NSFileManager defaultManager];
if (clean && [fm fileExistsAtPath:newDirPath])
{
[fm removeItemAtPath:newDirPath error:&error];
if (error != nil)
{
NSLog(#"Error while renameDir %# as %# :\n%#",dirPath,newDirPath,error);
return NO;
}
}
//Make sure container directories exist
NSString *newDirContainer = [newDirPath stringByDeletingLastPathComponent];
if (![fm fileExistsAtPath:newDirContainer])
{
[fm createDirectoryAtPath:newDirContainer withIntermediateDirectories:YES attributes:nil error:&error];
}
if (error==nil)
{
[fm moveItemAtPath:dirPath toPath:newDirPath error:&error];
}
if (error!=nil)
{
NSLog(#"error while moveItemAtPath : %#",error);
}
return (error==nil);
}
This always work
NSLog (#"Copying download file from %# to %#", aPath, bPath);
if ([[NSFileManager defaultManager] fileExistsAtPath: bPath]) {
[[NSFileManager defaultManager] removeItemAtPath: bPath
error: &error];
}
if (![[NSFileManager defaultManager] copyItemAtPath: aPath
toPath: bPath
error: &error]){}
if ([[NSFileManager defaultManager] removeItemAtPath: aPath
error: &error]) {}
This is good article for renaming, deleting and create files.
// For error information
NSError *error;
// Create file manager
NSFileManager *fileMgr = [NSFileManager defaultManager];
// Point to Document directory
NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
// Rename the file, by moving the file
NSString *filePath2 = [documentsDirectory stringByAppendingPathComponent:#"file2.txt"];
// Attempt the move
if ([fileMgr moveItemAtPath:filePath toPath:filePath2 error:&error] != YES)
NSLog(#"Unable to move file: %#", [error localizedDescription]);
// Show contents of Documents directory
NSLog(#"Documents directory: %#",
[fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error]);
http://iosdevelopertips.com/data-file-management/iphone-file-system-creating-renaming-and-deleting-files.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.