How to avoid overwriting files on iPhone Documents folder? - iphone

I need to write files containing NSArrays into the Documents folder of my iPhone application. Next time I need to create a new file, not overwriting the previous one.
I tried like this, but it only writes doc0 and doc1.
allDocs in an NSArray declared elsewhere.
What's wrong? Thank you!
NSString *myDoc;
NSString *temp;
for (int i = 0; i < [allDocs count]; ++i){
NSFileManager* fileMgr = [NSFileManager defaultManager];
myDoc = [NSString stringWithFormat:#"doc%d.dat", i];
NSString* currentFile = [documentsDirectory stringByAppendingPathComponent:myDoc];
BOOL fileExists = [fileMgr fileExistsAtPath:currentFile];
if (fileExists == NO){
temp = [NSString stringWithFormat:#"doc%d.dat", i];
break;
} else {
temp = [NSString stringWithFormat:#"doc%d.dat",i++];
break;
}
}
NSString *myArray = [documentsDirectory stringByAppendingPathComponent:myDoc];
NSMutableArray *myMutableArray = [[NSMutableArray alloc] initWithContentsOfFile: myArray];
if(myMutableArray == nil)
{
myMutableArray = [[NSMutableArray alloc] initWithCapacity:10];
myMutableArray = anotherArray;
}
[myMutableArray writeToFile:myArray atomically:YES];

You break out of the for loop on the first iteration each time whether the file is found or not. You should be looping with incremented values for i until fileExists is false.
- (BOOL) workFileExists:(NSString *)name {
NSFileManager *fm = [NSFileManager defaultManager];
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString *filename = [name stringByAppendingString:#".swrk"];
return [fm fileExistsAtPath:[path stringByAppendingPathComponent:filename]];
}
- (NSString *)uniqueUntitledName {
NSString *untitled = #"Untitled";
NSString *name = untitled;
int i = 1;
while ([self workFileExists:name]) {
name = [NSString stringWithFormat:#"%#%d", untitled, i];
i++;
}
return name;
}

UIImage *imageForShare = [UIImage imageNamed:#"anyImage.jpg"];
NSString *stringPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:#"New Folder"];
// New Folder is your folder name
NSError *error = nil;
//in this method you are checking the path is exist or not for Folder Name
if (![[NSFileManager defaultManager] fileExistsAtPath:stringPath])
[[NSFileManager defaultManager] createDirectoryAtPath:stringPath withIntermediateDirectories:NO attributes:nil error:&error];
//now checking the image name already exist or not
NSString *fileName = [stringPath stringByAppendingFormat:#"/image.jpg"];
if (![[NSFileManager defaultManager] fileExistsAtPath:fileName])
{
NSLog(#"Path is available.");
NSData *data = UIImageJPEGRepresentation(imageForShare, 1.0);
[data writeToFile:fileName atomically:YES];
}
else
{
NSLog(#"Path doesn't exist, same name of image is already exist.");
}
Thank You!!

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 obtain the size of a Application Directory in iPhone?

(NSString *)
getApplicationUsage{
double directorySizeInBytes = 0.0f;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationDirectory, NSUserDomainMask, YES);
NSString *pathStr = [paths objectAtIndex:0];
pathStr = [pathStr stringByDeletingLastPathComponent]; //REMOVE THE LAST PATH COMPONENT i.e /Applications
NSDirectoryEnumerator *enumrator = [[NSFileManager defaultManager] enumeratorAtPath:pathStr];
for (NSString *itemPath in enumrator) {
itemPath = [pathStr stringByAppendingPathComponent:itemPath];
NSDictionary *attr = [[NSFileManager defaultManager] attributesOfItemAtPath:itemPath error:nil];
directorySizeInBytes = directorySizeInBytes + [[attr objectForKey:NSFileSize] doubleValue];
}
NSString *applicationUsage = [NSString stringWithFormat:#"%0.0f MB",directorySizeInBytes /1000000];
return applicationUsage;
}
How about this?
- (unsigned long long) sizeOfFolderAtPath:(NSString *)path {
NSArray *files = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:path error:nil];
NSEnumerator *enumerator = [files objectEnumerator];
NSString *fileName;
unsigned long long size = 0;
while (fileName = [enumerator nextObject]) {
size += [[[NSFileManager defaultManager] fileAttributesAtPath:[folderPath stringByAppendingPathComponent:fileName] traverseLink:YES] fileSize];
}
return size;
}

Load all files in the app bundle containing a string in their filename into a NSMutableArray?

So I have a folder called "content" in my app's bundle . I would need to load all files, which contain a string, I provide (for example "dog"), in their filename into a NSMutableArray. How can I do this, if it even is possible?
Thanks a lot in advance!
NSMutableArray *resultFiles = [NSMutableArray array];
NSFileManager *fm = [[NSFileManager alloc] init];
NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
NSError *error = nil;
NSArray *files = [fm contentsOfDirectoryAtPath:bundlePath error:&error];
[fm release];
if (!error) {
for (NSString *filename in files) {
NSRange range = [filename rangeOfString:#"dog"];
if (!(range.location == NSNotFound && range.length == 0)) {
// filename contains "dog"
[resultFiles addObject:filename];
}
}
}

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