Deleting in NSDocumentDirectory - iphone

I save in NSDocumentDirectory this way:
NSLog(#"%#", [info objectAtIndex:i]);
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask ,YES );
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:#"Images%d.png", i]];
ALAssetRepresentation *rep = [[info objectAtIndex: i] defaultRepresentation];
UIImage *image = [UIImage imageWithCGImage:[rep fullResolutionImage]];
//----resize the images
image = [self imageByScalingAndCroppingForSize:image toSize:CGSizeMake(256,256*image.size.height/image.size.width)];
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:savedImagePath atomically:YES];
I know how to delete all the images in NSDocumentDirectory.
But I was wondering on how to delete all of the images with the name of oneSlotImages.
Thanks

Try this ,just copy this code,your images with name oneSlotImages,will be removed from DocumentDirectory ,its just simple :
NSArray *directoryContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject] error:NULL];
if([directoryContents count] > 0)
{
for (NSString *path in directoryContents)
{
NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:path];
NSRange r =[fullPath rangeOfString:#"oneSlotImages"];
if (r.location != NSNotFound || r.length == [#"oneSlotImages" length])
{
[[NSFileManager defaultManager] removeItemAtPath:fullPath error:nil];
}
}
}

Have you looked at NSFileManager's methods? Maybe something like this called in a loop for all of your images.
[[NSFileManager defaultManager] removeItemAtPath:imagePath error:NULL];

Use like,
NSArray *dirFiles = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:strDirectoryPath error:nil];
NSArray *zipFiles = [dirFiles filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"self CONTAINS[cd] %#", #"oneSlotImages"]];
The array zipFiles contains the names of all the files we filtered. Thus by appending the filenames with complete path of document directory with in a loop, you can make the full filepath of all the filtered files in the array. Then you can use a loop and call the method of NSFileManager object like below
[fileManager removeItemAtPath: strGeneratedFilePath error: &err];
which removes the itm at path from the directory.
By this way you can filter out the filenames contains oneSlotImages. So you can prefer to delete this ones. Hope this helps you.

As this is an old question now and also above answers shows how to delete by image name.What if I want to delete everything from NSDocumentDirectory at one shot, use the below code.
// Path to the Documents directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
if ([paths count] > 0)
{
NSError *error = nil;
NSFileManager *fileManager = [NSFileManager defaultManager];
// Print out the path to verify we are in the right place
NSString *directory = [paths objectAtIndex:0];
NSLog(#"Directory: %#", directory);
// For each file in the directory, create full path and delete the file
for (NSString *file in [fileManager contentsOfDirectoryAtPath:directory error:&error])
{
NSString *filePath = [directory stringByAppendingPathComponent:file];
NSLog(#"File : %#", filePath);
BOOL fileDeleted = [fileManager removeItemAtPath:filePath error:&error];
if (fileDeleted != YES || error != nil)
{
// Deal with the error...
}
}
}

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 copy one image and save as diff. name in document directory

In my document directory one image is their, with name Image1.
I want copy same image with name Image2 in document directory folder.
Please, suggest me how can i do that?
refer a following code.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [paths objectAtIndex:0];
NSString *imagePath1= [documentDirectory stringByAppendingPathComponent:#"image1.png"];
NSString *imagePath2= [documentDirectory stringByAppendingPathComponent:#"image2.png"];
[[NSFileManager defaultManager] copyItemAtPath:imagePath1 toPath:imagePath2 error:nil];
Get he data from first image and save the same data with another name like:
NSData *data = UIImageJPEGRepresentation(image1, 1.0);
NSString *str=#"image2.png"
NSString *fileName = [[stringPath stringByAppendingFormat:#"/"] stringByAppendingFormat:str];
NSString *stringPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
[data writeToFile:fileName atomically:YES];
I have two mathed of Fatch image and save image:
You fatch image that save in Document directory and then pass it to save image with different name:
-(UIImage *)loadImage:(NSString *)name
{
NSString* documentsDirectory=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES) objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:name];
UIImage *res = [UIImage imageWithContentsOfFile:fullPath];
return res;
}
-(void)saveImage:(UIImage *)image withName:(NSString *)name
{
NSData *data = UIImageJPEGRepresentation(image, 1);
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString* documentsDirectory=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES) objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:name];
[fileManager createFileAtPath:fullPath contents:data attributes:nil];
}

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

How to find the contents in documents directory in iPhone

i want to know the contents in a directory either its documents or any other.
if there is a file or more than one i need those file names.
actually i am creating the export directory in documents directory..
and if export is empty then i am copying the zip file from main bundle to export folder
but the following code is not working. though the export is empty its not going in to that if block..r there any hidden files..? and in the last for loop its not doing any thing.
how to do this.
please help me out
self.fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
self.documentsDir = [paths objectAtIndex:0];
//creating folder 'export' to recieve the file from iTunes
NSString *srcFilePath = [NSString stringWithFormat:#"%#/export", self.documentsDir];
[fileManager createDirectoryAtPath:srcFilePath
withIntermediateDirectories:NO
attributes:nil
error:nil];
//copying the zip file into exprort from bundle if export is empty
if(![fileManager fileExistsAtPath:srcFilePath]) {
NSLog(#"File exists at path: %#", srcFilePath);
NSString *resZipfile = [[NSBundle mainBundle] pathForResource:#"sample" ofType:#"zip"
inDirectory:#"pckg"];
NSLog(#"zip file path ...%#", resZipfile);
NSData *mainBundleFile = [NSData dataWithContentsOfFile:resZipfile];
[[NSFileManager defaultManager] createFileAtPath:srcFilePath
contents:mainBundleFile
attributes:nil];
}
NSString *eachPath;
NSDirectoryEnumerator *dirEnum = [fileManager enumeratorAtPath:srcFilePath];
for(eachPath in dirEnum) NSLog(#"FILE: %#", eachPath);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSFileManager *manager = [[NSFileManager alloc] init];
NSDirectoryEnumerator *fileEnumerator = [manager enumeratorAtPath:documentsPath];
for (NSString *filename in fileEnumerator) {
// Do something with file
}
[manager release];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsPath = [paths objectAtIndex:0];
NSString *srcFilePath = [NSString stringWithFormat:#"%#/export", self.documentsDir];
BOOL isDir;
BOOL exists = [[NSFileManager defaultManager] fileExistsAtPath:srcFilePath] isDirectory:&isDir];
if (!exists && !isDir) {
[fileManager createDirectoryAtPath:srcFilePath
withIntermediateDirectories:NO
attributes:nil
error:nil];
NSLog(#"File exists at path: %#", srcFilePath);
NSString *resZipfile = [[NSBundle mainBundle] pathForResource:#"sample" ofType:#"zip"
inDirectory:#"pckg"];
NSLog(#"zip file path ...%#", resZipfile);
NSData *mainBundleFile = [NSData dataWithContentsOfFile:resZipfile];
[[NSFileManager defaultManager] createFileAtPath:srcFilePath
contents:mainBundleFile
attributes:nil];
Swift 4 version:
guard let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first,
let fileEnumerator = fileManager.enumerator(atPath: path) else {
return
}
let fileNames = fileEnumerator.flatMap { $0 as? String } //Here You will have Array<String> with files in current folder and subfolders of your application's Document directory