iOS: write data to json file programatically - objective-c

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

Related

Save locally generated PDF to app's documents folder in iOS8

It would seem that my apps no longer are able to save files to their documents folder when doing this:
NSString *path = [documentsDirectory stringByAppendingPathComponent:fileName];
NSData *dta = [[NSData alloc] init];
dta = [NSData dataWithContentsOfFile:path];
NSLog(#"writing file: %#", path);
if ([dta writeToFile:path options:NSAtomicWrite error:nil] == NO) {
NSLog(#"writeToFile error");
}else {
NSLog(#"Written: %#", path);
[self addSkipBackupAttributeToItemAtURL:[NSURL fileURLWithPath:path]];
}
I do get "Written" in the log with the full path:
Written: /var/mobile/Containers/Data/Application/ECBCD65D-A990-4758-A07F-ECE48E269278/Documents/9d440408-4758-4219-9c9c-12fe69cf82f2_pdf.pdf
And as long as I don't quit the app I can load the PDF in a UIWebView like this (pdfPath is a string that I pass to the function that loads the PDF file):
[www loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:pdfPath]]];
Any help at all is as always greatly appreciated.
Okay, after mucking about I found that since the documents directory changes path every time I run the app, I had to:
Write the file to the documents folder with the complete path to
the file:
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask ,YES );
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent: fileName];
NSData *dta = [[NSData alloc] init];
dta = [NSData dataWithContentsOfFile:path];
if ([dta writeToFile:path options:NSAtomicWrite error:nil] == NO) {
NSLog(#"writeToFile error");
}else {
NSLog(#"Written: %#", path);
[self addSkipBackupAttributeToItemAtURL:[NSURL fileURLWithPath:path]];
}
Save only the file name to my database
Load the file by using the full newly generated Documents directory path and append the file name from my database:
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent: pdfPath];

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

Saving images to a directory

Hi I want to save an image to a directory, I pass the NSData and do what I think will save the file in a directory I create but the problem is that it doesn't save. This is what I have so far. Why doesn't the initWithContentsOfURL:encoding:error: work, it returns null but the other method I used works? The main problem is WRITETOURL which returns a 0 which i think means that the information wasn't stored properly, any tips?
NSFileManager *fm = [[NSFileManager alloc] init];
NSArray * directoryPaths = [fm URLsForDirectory:NSCachesDirectory inDomains:NSUserDomainMask];
NSLog(#"%#", directoryPaths);
NSURL* dirPath = nil;
dirPath = [[directoryPaths objectAtIndex:0] URLByAppendingPathComponent:[NSString stringWithFormat:#"photos.jpeg"]];
NSError* theError = nil;
[fm createDirectoryAtURL:dirPath withIntermediateDirectories:YES attributes:nil error:&theError];
UIImage* photoToStore = [UIImage imageWithData:photoToSave];
NSString *pathContainingPhoto = [[NSString alloc] initWithFormat:#"%#.jpeg", UIImageJPEGRepresentation(photoToStore, 1.0)];
NSError *error = nil;
BOOL OK = [pathContainingPhoto writeToURL:dirPath atomically:YES encoding:NSUTF8StringEncoding error:&error];
NSLog(#"OK = %d", OK); //Returns 0
NSLog(#"%#", dirPath);
//WHY DOESNT THIS VERSION WORK?
// NSString *pathToFile = [[NSString alloc] initWithContentsOfURL:dirPath encoding:NSUTF8StringEncoding error:&error];
NSLog(#"%#", pathToFile);
NSString* pathToFile = [NSString stringWithContentsOfURL:dirPath encoding:nil error:nil];
NSArray *dirContents = [fm contentsOfDirectoryAtPath:pathToFile error:nil];
NSLog(#"%#", dirContents);
Do like this and int count in .h file and set its intial value count = 0; in viewDidLoad:
NSString *stringPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:[NSString stringWithFormat:#"Image_%d.png",count];
error = nil;
if (![[NSFileManager defaultManager] fileExistsAtPath:stringPath]) // removing item it already exuts
{
[[NSFileManager defaultManager] removeItemAtPath:stringPath error:&error];
}
if(photoToSave) // nsdata of image that u have
{
[photoToSave writeToFile:stringPath atomically:YES];
}
count++; // maintaining count of images

Delete empty folders in iOS?

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

NSFileHandle fileHandleForWritingAtPath: return null!

my iPad app has a small download facility, for which I want to append the data using an NSFileHandle. The problem is the creation call only returns null file handles. What could be the problem? Here is the three lines of code that are supposed to create my file handle:
NSString *applicationDocumentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
self.finalPath = [applicationDocumentsDirectory stringByAppendingPathComponent: self.fileName];
NSFileHandle *output = [NSFileHandle fileHandleForWritingAtPath:self.finalPath];
I checked the file path, and I could see nothing wrong.
TYIA
fileHandleForWritingAtPath is not a “creation” call. The documentation explicitly states: “Return Value: The initialized file handle, or nil if no file exists at path” (emphasis added). If you wish to create the file if it does not exist, you’d have to use something like this:
NSFileHandle *output = [NSFileHandle fileHandleForWritingAtPath:self.finalPath];
if(output == nil) {
[[NSFileManager defaultManager] createFileAtPath:self.finalPath contents:nil attributes:nil];
output = [NSFileHandle fileHandleForWritingAtPath:self.finalPath];
}
If you want to append to the file if it already exists, use something like [output seekToEndOfFile]. Your complete code would then look as follows:
NSString *applicationDocumentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
self.finalPath = [applicationDocumentsDirectory stringByAppendingPathComponent: self.fileName];
NSFileHandle *output = [NSFileHandle fileHandleForWritingAtPath:self.finalPath];
if(output == nil) {
[[NSFileManager defaultManager] createFileAtPath:self.finalPath contents:nil attributes:nil];
output = [NSFileHandle fileHandleForWritingAtPath:self.finalPath];
} else {
[output seekToEndOfFile];
}
Get documents directory path
+(NSURL *)getDocumentsDirectoryPath
{
return [[[NSFileManager defaultManager]URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask]lastObject];
}
Save text to end of the file
if file doesnt exist create it and write data
+(void)saveText:(NSString *)textTobeSaved atPath:(NSString*)fileName
{
NSString *filePath = [NSString stringWithFormat:#"%#.text",fileName];
NSString *path = [[self getDocumentsDirectoryPath].path
stringByAppendingPathComponent:filePath];
NSFileHandle *fileHandler = [NSFileHandle fileHandleForWritingAtPath:path];
if(fileHandler == nil) {
[[NSFileManager defaultManager] createFileAtPath:path contents:nil attributes:nil];
fileHandler = [NSFileHandle fileHandleForWritingAtPath:path];
} else {
textTobeSaved = [NSString stringWithFormat:#"\n-----------------------\n %#",textTobeSaved];
[fileHandler seekToEndOfFile];
}
[fileHandler writeData:[textTobeSaved dataUsingEncoding:NSUTF8StringEncoding]];
[fileHandler closeFile];
}
get text from file with specified filename
+(NSString *)getTextFromFilePath:(NSString *)fileName
{
NSString *filePath = [NSString stringWithFormat:#"%#.text",fileName];
NSString *path = [[self getDocumentsDirectoryPath].path
stringByAppendingPathComponent:filePath];
NSLog(#"%#",path);
if(path!=nil)
{
NSString *savedString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
return savedString;
}else{
return #"";
}
}
Delete file
+(void)deleteFile:(NSString *)fileName
{
NSString *filePath = [NSString stringWithFormat:#"%#.text",fileName];
NSString *path = [[self getDocumentsDirectoryPath].path
stringByAppendingPathComponent:filePath];
NSFileHandle *fileHandler = [NSFileHandle fileHandleForWritingAtPath:path];
if(fileHandler != nil) {
[[NSFileManager defaultManager]removeItemAtPath:path error:nil];
}
}