Delete empty folders in iOS? - objective-c

I have plenty of empty temporary folders in app's Document folder.
How to delete them all?
I tried:
NSArray *folders = [[NSFileManager defaultManager]contentsOfDirectoryAtURL:[self applicationDocumentsDirectory] includingPropertiesForKeys:[NSArray arrayWithObject:#"NSURLIsDirectoryKey"] options:0 error:nil];
if (folders) {
for (NSURL *url in folders) {
[[NSFileManager defaultManager]removeItemAtURL:url error:nil];
}
}
but it deletes all, not only folders

This snippet of code deletes only directiories that are empty.
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSArray *files = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:nil];
for (NSString *file in files) {
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:file];
NSError *error;
if ([[fileManager contentsOfDirectoryAtPath:fullPath error:&error] count]==0) {
// check if number of files == 0 ==> empty directory
if (!error) {
// check if error set (fullPath is not a directory and we should leave it alone)
[fileManager removeItemAtPath:fullPath error:nil];
}
}
}
If you simply want to delete all directories (both empty and not empty) the snippet can be simplified into this:
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSArray *files = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:nil];
for (NSString *file in files) {
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:file];
if ([fileManager contentsOfDirectoryAtPath:fullPath error:nil])
[fileManager removeItemAtPath:fullPath error:nil];
}

Related

iOS: write data to json file programatically

My json file look like this:
{
"images": [
"straight up kick.png",
"women kick.png",
"Taekwondo Kanji vertical.png",
"face kick3.png",
"flexibility.png",
"Punch.png",
"hook kick.png",
"front kick 2.png"
]
}
i am reading above json programmatically like below:
NSString *path = [[NSBundle mainBundle] pathForResource:#"generated" ofType:#"json"];
NSData *data = [NSData dataWithContentsOfFile:path];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSMutableArray * jsonimages = [dict objectForKey:#"images"];
NSLog(#"images %#", jsonimages);
i want to add more items to array named as jsonimages by writing to json file programmatically.
Json file name is generated.json.
Any help would be appreciated.
- (void)writeStringToFile:(NSString*)aString {
// Build the path, and create if needed.
NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* fileName = #"generated.json";
NSString* fileAtPath = [filePath stringByAppendingPathComponent:fileName];
if (![[NSFileManager defaultManager] fileExistsAtPath:fileAtPath]) {
[[NSFileManager defaultManager] createFileAtPath:fileAtPath contents:nil attributes:nil];
}
// The main act...
[[aString dataUsingEncoding:NSUTF8StringEncoding] writeToFile:fileAtPath atomically:NO];
}
- (NSString*)readStringFromFile {
// Build the path...
NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* fileName = #"generated.json";
NSString* fileAtPath = [filePath stringByAppendingPathComponent:fileName];
// The main act...
return [[NSString alloc] initWithData:[NSData dataWithContentsOfFile:fileAtPath] encoding:NSUTF8StringEncoding];
}

Objective c -enumaeratorAtPath: Not Working at root level folders

I am trying to enumerate files and folders at root level
(/Users/Myname/Desktop or /Users/Myname/Documents),[enumarator nextobject] always gives nil value.
How can i solve this issue.
NSDirectoryEnumerator* enumerator = [[NSFileManager defaultManager] enumeratorAtPath:#"/Users/Myname/Desktop"];
NSString *content= [enumerator nextObject];//content always nil.
Try this:
NSFileManager *fileManager = [NSFileManager defaultManager];
NSDirectoryEnumerator * emuerator = [fileManager enumeratorAtPath:#"/usr/Myname/Desktop"];
NSString *filename; while ((filename = [emuerator
nextObject]))
{
NSLog (#"file! %#", filename);
}
OR
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSFileManager *manager = [[NSFileManager alloc] init];
NSDirectoryEnumerator *emuerator= [manager enumeratorAtPath: #"/usr/Myname/Desktop"];
for (NSString *filename in emuerator) {
// Do something with file
}
[manager release];

objective c - copy files into existing directory

How do I copy files from DIR1 to DIR2 , without copying the entire directory?
I'm trying to copy files to a folder that contains other files, so I don't want to create a new folder. which what the following code does:
[[NSFileManager defaultManager] copyItemAtPath:sourceDir toPath:destDir error:&err];
Get all the contents in the folder
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *fileList = [[NSFileManager defaultManager] directoryContentsAtPath:documentsDirectory];
Enumerate over the files list and copy them.
[fileList enumerateObjectsUsingBlock:^(NSString *string, NSUInteger index, BOOL *stop) {
[[NSFileManager defaultManager]copyItemAtPath:strdestination toPath:toPath error:&Error];
}];
this is how I've done it:
NSArray *sourceFiles = [fileManager contentsOfDirectoryAtPath:sourceDir error:NULL];
NSError *copyError = nil;
for (NSString *currentFile in sourceFiles)
{
BOOL isDirectory = NO;
NSString* fullFilePath = [NSString stringWithFormat:#"%#/%#",sourceDir,currentFile];
if ([fileManager fileExistsAtPath:fullFilePath isDirectory:&isDirectory] && !isDirectory)
{
if (![fileManager copyItemAtPath:[sourceDir stringByAppendingPathComponent:currentFile] toPath:[destDir stringByAppendingPathComponent:currentFile] error:&copyError])
{
NSLog(#"Error Copying: %#", [copyError description]);
}
}
}

How do I download an image from a URL and save it to my computer?

How would I download an image from a URL, and have that saved to the computer using Objective-C? This is what I got so far:
NSString *documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
UIImage *imageFromURL = [self getImageFromURL:#"https://www.google.com/images/srpr/logo11w.png"];
[self saveImage:imageFromURL withFileName:#"Google Logo" ofType:#"png" inDirectory:documentsDirectoryPath];
UIImage *imageFromWeb = [self loadImage:#"Google Logo" ofType:#"png" inDirectory:documentsDirectoryPath];
Xcode complains about UIIMage, trying to replace with NSImage. It also complains about an undeclared identifier 'self'.
I need to make an HTTP call to perform this as well. Explain this to me like I'm 5.
Here is the code to Save the image into document Directory.
-(void)saveImagesInLocalDirectory
{
NSString * documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *imgName = #"image.png";
NSString *imgURL = #"www.example.com/image/image.png";
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *writablePath = [documentsDirectoryPath stringByAppendingPathComponent:imgName];
if(![fileManager fileExistsAtPath:writablePath]){
// file doesn't exist
NSLog(#"file doesn't exist");
if (imgName) {
//save Image From URL
[self getImageFromURLAndSaveItToLocalData:imgName fileURL:imgURL inDirectory:documentsDirectoryPath];
}
}
else{
// file exist
NSLog(#"file exist");
}
}
-(void) getImageFromURLAndSaveItToLocalData:(NSString *)imageName fileURL:(NSString *)fileURL inDirectory:(NSString *)directoryPath {
NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]];
NSError *error = nil;
[data writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#", imageName]] options:NSAtomicWrite error:&error];
if (error) {
NSLog(#"Error Writing File : %#",error);
}else{
NSLog(#"Image %# Saved SuccessFully",imageName);
}
}
And this is the one method code..
-(void)saveImagesInLocalDirectory
{
NSString * documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *imgName = #"image.png";
NSString *imgURL = #"www.example.com/image/image.png";
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *writablePath = [documentsDirectoryPath stringByAppendingPathComponent:imgName];
if(![fileManager fileExistsAtPath:writablePath]){
// file doesn't exist
NSLog(#"file doesn't exist");
//save Image From URL
NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString: imgURL]];
NSError *error = nil;
[data writeToFile:[documentsDirectoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#", imgName]] options:NSAtomicWrite error:&error];
if (error) {
NSLog(#"Error Writing File : %#",error);
}else{
NSLog(#"Image %# Saved SuccessFully",imgName);
}
}
else{
// file exist
NSLog(#"file exist");
}
}
This is my solution!
+(BOOL)downloadMedia :(NSString*)url_ :(NSString*)name{
NSString *stringURL = url_;
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,name];
[urlData writeToFile:filePath atomically:YES];
return YES;
}
return NO;
}
+(UIImage*)loadMedia :(NSString*)name{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:name];
UIImage *img_ = [UIImage imageWithContentsOfFile:getImagePath];
return img_;
}

Delete file obj c

I am creating files with the following code
NSString *docPath = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString *filename = #"xyz123.data";
docPath = [NSString stringWithFormat:#"%#/%#", docPath, filename];
NSError *error = nil;
[data writeToFile:docPath options:0 error:&error];
To delete files I use the following
NSFileManager *manager = [NSFileManager defaultManager];
NSError *error = nil;
NSString *path = #"xyz123.data";
//NSString *path = #"Documents/xyz123.data";
[manager path error:&error];
But neither the first nor the second path seem to work, I always get the error "no such file or directory".
You used NSHomeDirectory() stringByAppendingPathComponent in the file creation, but not in either path when you try to delete the file. Try:
[manager removeItemAtPath:[NSHomeDirectory() stringByAppendingPathComponent:#"Documents/xyz123.data"] error:&error]
Try this:
NSString *docPath = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString *filePath = [docPath stringByAppendingPathComponent:#"xyz123.data"];
NSError *error = nil;
[data writeToFile:filePath options:0 error:&error];
[[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];