how to write json file in ios - ios

Here i am reading and writing a json file.
Reading is done correctly but while i am writing a file it doesn't write data in json file.
Here is my code.
//reading Json file....
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"bookmark" ofType:#"json"];
NSData *content = [[NSData alloc] initWithContentsOfFile:filePath];
NSArray *bookmarkJson=[NSJSONSerialization JSONObjectWithData:content options:0 error:nil];
//this contains array's of dictionary....
NSDictionary *newBookmark=#{#"index":#"1.1.1.1",#"text":#"Header",#"htmlpage":#"page_name"};
//take new array to add data with previous one
NSMutableArray *temp=[[NSMutableArray alloc]initWithArray:bookmarkJson];
// add object to new array...
[temp insertObject:newBookmark atIndex:0];
//now serialize temp data....
NSData *serialzedData=[NSJSONSerialization dataWithJSONObject:temp options:0 error:nil];
NSString *saveBookmark = [[NSString alloc] initWithBytes:[serialzedData bytes] length:[serialzedData length] encoding:NSUTF8StringEncoding];
//now i write json file.....
[saveBookmark writeToFile:#"bookmark.json" atomically:YES encoding:NSUTF8StringEncoding error:nil];
In "saveBookmark" (NSString)object i got correct file format but in bookmark.json file i didn't got any new values.
Please help me with this......

EDIT: As correctly pointed out by #IulianOnofrei, use the document directory to read/write files and not the resources directory.
Use these methods to read and write data, and your problem should be solved:
- (void)writeStringToFile:(NSString*)aString {
// Build the path, and create if needed.
NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* fileName = #"bookmark.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 = #"bookmark.json";
NSString* fileAtPath = [filePath stringByAppendingPathComponent:fileName];
// The main act...
return [[NSString alloc] initWithData:[NSData dataWithContentsOfFile:fileAtPath] encoding:NSUTF8StringEncoding];
}
Code courtesy from another SO answer found here: Writing and reading text files on the iPhone
And of course, the first time you try to read this file from the documents directory you won't get anything, so maybe the first step would be to copy the file there if it does not exist.
Hope this helps.

Related

Create a .json or .txt file public in iOS?

I want to create a .json file and .text file public so that it can be read by NSItemProvider. I want to create file programmatically.
Can you refer this link, that will be helpful to play around file creation, deletion etc...
http://www.ios-developer.net/iphone-ipad-programmer/development/file-saving-and-loading/using-the-document-directory-to-store-files
Use the following code to write/create a .txt file in your app's Documents directory :
NSError *error;
NSString *stringToWrite = #"hello>!!new file created..";
NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:#"myfile.txt"];
[stringToWrite writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
To read/fetch the text file:
NSString *str = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
NSLog(#"%#", str);

How To Down and store the Text File on Local Cache

I am developing an IOS app..Download data From URL and save on local cache..but i am using this code..first time data can stored in Local cache and also read on the text field..but Delete the app on simulator and run the and again store the text file on local cache..file can't be store..Any help or advice is greatly appreciated. thanks in advance.
NSURL *url = [NSURL URLWithString:#"http://webapp.opaxweb.net/books/"];
NSData *data_file = [[NSData alloc]initWithContentsOfURL:url];
NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent]stringByAppendingPathComponent:#"Documents"]];
NSString *filepath = [resourceDocPath stringByAppendingPathComponent:#"gurugranthsahib.txt"];
[data_file writeToFile:filepath atomically:YES];
NSLog(#"%#",filepath);
NSString* content = [NSString stringWithContentsOfFile:filepath
encoding:NSUTF8StringEncoding
error:NULL];
iOS does not allow writing to the app bundle.
Generally data is written to the Documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths firstObject];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];
Note:
It is much better practice to use a method call that has an error parameter so when there is an error the error can be examined. In this case you could use:
NSError *error;
BOOL status = [string writeToFile:filePath options:NSDataWritingAtomic error:&error];
if (status == NO) {
NSLog(#"error: %#", error)
}

How to create a new text file to write to in objective c ipad app

How would I go about creating a new text file in my program so that I can write content to it? I already understand how to write content but I haven't been able to find anything (anything easy to understand) on the subject.
Use this method:
+ (id)stringWithContentsOfFile:(NSString *)path
usedEncoding:(NSStringEncoding *)enc
error:(NSError **)error
An example:
NSString* path = [[NSBundle mainBundle] pathForResource:#"Example"
ofType:#"txt"];
NSError *error = nil;
NSString* content = [NSString stringWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:&error];
if(error)
{
NSLog(#"ERROR while loading from file: %#", error);
}
Write to a file works this way:
Use this method:
- (BOOL)writeToFile:(NSString *)path
atomically:(BOOL)useAuxiliaryFile
encoding:(NSStringEncoding)enc
error:(NSError **)error
Example:
[text writeToFile:path atomically:NO encoding:NSUTF8StringEncoding error:nil];
Mistake:
Can't just write to bundle path. Need to copy it to Documents Directory.
-(void)copyBundleToDocuments
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [documentPaths objectAtIndex:0];
NSString *documentPlistPath = [documentsDirectory stringByAppendingPathComponent:#"Example.txt"];
NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
NSString *bundlePlistPath = [bundlePath stringByAppendingPathComponent:#"Example.txt"];
NSError *error;
BOOL success = [fileManager copyItemAtPath:bundlePlistPath toPath:documentPlistPath error:&error];
if (success)
{
[text writeToFile:documentPlistPath atomically:NO encoding:NSUTF8StringEncoding error:nil];
}
}
Your question is so broad one could drive a truck (or lorry, in UK English) through the middle of it.
But in general, you could add a UITextView to one of your view controllers.
And when you are ready to save, you could take the contents of the text view (which is a NSString), and save it to a file via the NSString writeToFile methods.
And you can load the text view later on via NSString's "initFromFile" method, as long as you know the path to that file.
Here are other questions that people have asked that may help you out.
You can use UITextView to write text
save the file using
[txtView.text writeToFile:filePath atomically:NO encoding:NSUTF8StringEncoding error:nil];
Get the TextFile content using
NSString* content = [NSString stringWithContentsOfFile:filePath
encoding:NSUTF8StringEncoding
error:NULL];

Zip library issue

So I am using this library: https://github.com/flyingdolphinstudio/Objective-Zip
I implemented it and am trying to take a UIImage and NSString and make it a .png and .txt in the .zip file, respectively.
Now these are my 2 concerns, I am trying to save the *zipFile below to the documents directory.
Now with the dropbox API, how come I can't just provide the file itself and skip the path. It seems like I HAVE to save the .zip to the documents directory first and then get the path so I can then upload it to dropbox. Do I have to do that?
In the ...writeToFile line, I am getting a warning that ZipFile may not respond to writeToFile so how would I properly save it to the documents directory?
Anyway this is the code I have so far:
NSString *filename = [NSString stringWithFormat:#"%#.zip", textField.text];
ZipFile *zipFile= [[ZipFile alloc] initWithFileName:filename mode:ZipFileModeCreate];
//Image
NSString *nameImage = #"Image.png";
NSMutableDictionary *theDictionary = [Singleton sharedSingleton].dictionary;
NSData *data = [theDictionary objectForKey:#"image"];
ZipWriteStream *writeImage = [zipFile writeFileInZipWithName:nameImage compressionLevel:ZipCompressionLevelBest];
[writeImage writeData:data];
[writeImage finishedWriting];
//Text
NSString *nameText = #"Text.txt";
NSData *dataText = [textView.text dataUsingEncoding:NSUTF8StringEncoding];
ZipWriteStream *writeText = [zipFile writeFileInZipWithName:nameText compressionLevel:ZipCompressionLevelBest];
[writeText writeData:dataText];
[writeText finishedWriting];
//Now we HAVE to save it to the documents directory to get it to work with dropbox
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory
NSString *filePath = [documentsPath stringByAppendingPathComponent:filename]; //Add the file name
[zipFile writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:NULL];
//Save to Dropbox
NSString *zipPath = [[NSBundle mainBundle] pathForResource:textField.text ofType:#"zip"];
[[self restClient] uploadFile:filename toPath:#"/" withParentRev:nil fromPath:zipPath];
So what am I doing wrong here?
Thanks!
It looks to me like ZipFile already writes to a file, so there's no need for something like writeToFile. Just initialize zipFile with the path you want, be sure to close the file at the end ([zipFile close]), and then upload to Dropbox as you would any other file.

Objective-Zip file folder structure ios

I have my App create a file, compress it into a .zip file, then attach it to an email. But the .zip file contains many directories before the actual file. Starting with the '/' which is a nameless folder and looks invisible to the people receiving it. The top level directory is '/', the next level is 'com'...
/var/mobile/Applications/CDA16BB231BDABABBA/Documents/data.txt
How can I remove all the directories and have the .zip file contain only the file?
Here's the code I have used...
NSError *error;
NSString *documentsDirectory = [NSHomeDirectory()
stringByAppendingPathComponent:#"Documents"];
NSString *filePath = [documentsDirectory
stringByAppendingPathComponent:#"data.txt"];
NSLog(#"string to write:%#",printString);
[printString writeToFile:filePath atomically:YES
encoding:NSUTF8StringEncoding error:&error];
////ZIP FILE/////
NSString *zipfilePath = [documentsDirectory stringByAppendingPathComponent:#"data.zip"];
[[NSFileManager defaultManager] removeItemAtPath: zipfilePath error: &error];
ZipFile *zipFile = [[ZipFile alloc]initWithFileName:zipfilePath mode:ZipFileModeCreate];
NSDictionary *attributes = [[NSFileManager defaultManager]attributesOfItemAtPath:zipfilePath error:&error];
NSDate *Date = [attributes objectForKey:NSFileCreationDate];
ZipWriteStream *stream = [zipFile writeFileInZipWithName:filePath fileDate:Date compressionLevel:ZipCompressionLevelBest];
NSData *data = [NSData dataWithContentsOfFile:filePath];
[stream writeData:data];
[stream finishedWriting];
[zipFile close];
The problem is that you are saying:
writeFileInZipWithName:filePath
The variable filePath contains that huge long name you are complaining about. It is the whole path from the top all the way down to your actual file.
Your file's name is #"data.txt", so what you want to say is:
writeFileInZipWithName:#"data.txt"

Resources