I'm basically trying to find a way to save a JSON server response, so can work on some app logic that relies on the response even when the server is no longer returning it. When I get the data back, I can print it out and it will look something like this:
<7b202254 7269704c 69737422 3a207b22 43757272 656e7454 696d6522 3a203134 30353037 33323836 ...
Is there any way I can create an instance of NSData using this information (NSData dataWithData?)? Or is there a way to create JSON dict/array with the JSON string?
TL;DR how do I save a JSON server response and add a debug option to fake the server response?
You can directly save the jsonData (NSData) into a file, and use it, see below
{
//Write NSData directly to file
[jsonData writeToFile:[self jsonFilePath] atomically:YES encoding:NSUTF8StringEncoding error:nil];
//Read from file
NSJSONSerialization *json=[NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:[self jsonFilePath]] options:0 error:nil];
//The json object can be used as an Array or, Dictionary
NSArray *array=(NSArray *)json;
//OR
NSDictionary *dic=(NSDictionary *)json;
}
-(NSString *)jsonFilePath{
return [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:#"file.json"];
}
Hope it helps.
Cheers.
You Json Response data is image data . You can store it in document directory as below.
NSData *webData = UIImageJPEGRepresentation(image1, 0.5);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:#"Profile1.jpeg"];
[webData writeToFile:savedImagePath atomically:YES];
Now in your Document Directory store image. check go to Iphone Simulator > Application > ProjectName > Documents
Store JSON in text file, as suggested by other.
Now where you want to fetch this text file data, you can use -
NSString *jsonFilepath = [[NSBundle mainBundle] pathForResource:#"jsonFile" ofType:#"text"];
// JSON Data
NSData *data = [NSData dataWithContentsOfFile: jsonFilepath];
// JSON String
NSString *jsonString = [[NSString alloc] initWithContentsOfFile:jsonFilepath encoding:NSUTF8StringEncoding error:nil];
Now you can perform all operation with JSON, as you want.
You can save your JSON Data as a plist in your App's Document Folder..
-(void)SaveResponse
{
NSError *error = nil;
NSData *JSONData = Your Current Data that received from server
NSMutableDictionary *objDictionary = [NSJSONSerialization
JSONObjectWithData:JSONData
options:NSJSONReadingAllowFragments
error:&error];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *strFilePath = [documentsDirectory stringByAppendingPathComponent:#"Response.plist"];
[objDictionary writeToFile:strFilePath atomically:YES];
}
Related
When there is no internet connection on device, i am storing the json in to a text file. But the problem is, if i do again it is getting replaced. Here is what i am doing for store into a text file. How to store multiple json object in a text file.When i get connection i need to post json to server.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
NSString *filePath = [docDir stringByAppendingPathComponent:#"File.json"];
[jsonString writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
Please advice.
That's not so straight forward as concatenating multiple JSON files does not result in a valid JSON file. To do this properly requires you to read and parse the existing JSON file, which will give you an NSArray or NSDictionary top-level object, then append the data from the new JSON file and write the whole thing out.
That is inefficient as you are processing old data.
Therefore I would suggest you write new data to a new file, using the current date/time for the filename, and when it's time to upload, read each of the files and upload them individually, one-at-a-time. Then delete each file as it's uploaded.
Use below method to append text to file
-(void) writeToLogFile:(NSString*)content{
content = [NSString stringWithFormat:#"%#\n",content];
//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
NSString *filePath = [docDir stringByAppendingPathComponent:#"File.json"];
NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:fileName];
if (fileHandle){
[fileHandle seekToEndOfFile];
[fileHandle writeData:[content dataUsingEncoding:NSUTF8StringEncoding]];
[fileHandle closeFile];
}
else{
[content writeToFile:fileName
atomically:NO
encoding:NSStringEncodingConversionAllowLossy
error:nil];
}
}
I want to update my local JSON file in the app when there is a new version of the file. I have the algorithm that checks if there is a new version or not.
But now, I need some code to change/update the local JSON for the online JSON.
I suggest you to use a .plist file as it can easily store a NSDictionary or NSArray (which can be translated from a JSON object)
try the code below:
//store plist file in documents directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = paths[0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"localJSON.plist"];
if([responseObject isKindOfClass:[NSArray class]])
{
//its an array
NSArray * dataToStore = jsonObject;
[dataToStore writeToFile:filePath atomically:YES];
}
else
{
//its a dictionary
NSDictionary * dataToStore = jsonObject;
[dataToStore writeToFile:filePath atomically:YES];
}
Imagine that you are reading json data from the server continuously. let's say, you are getting weather data. I want to show only data 2 hours back from now. Whenever user clicks on the play button, it would show weather data on the map.
How I could save json data first then show it on the map. Because that would enhance my application instead of connecting server , getting data and showing it at the same time. please just give me advice. Do I need to save it first as a plist or an array? Where should I keep this data before I simulate?
Storing it in the plist in the documents directory is a good way of saving data for later reference.If you want to save the JSON string you can also opt for NSUSerDefaults..(preferably if the string is not too large)
Saving to plist..
NSURL *url = [NSURL URLWithString:serverPath];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/myplist.plist", documentsDirectory];
[urlData writeToFile:filePath atomically:YES];
}
and retrieving it..
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat: #"%#/myplist.plist",documentsDirectory ] ];
NSData *retrievedData = [NSData dataWithContentsOfFile:filePath];
I am receiving a JSON response and am currenlty able to make use of the data within my app.
I would like to save this response to a file so I could reference within an JS file located inside my project. I have already requested this data once when the application is launched so why not save it to a file and reference that throughout so only one call is needed for the data.
The HTML files for my UIWebView are imported into my Xcode project using the "create folder reference" option and the path to my JS file is html->js->app.js
I want to save the response as data.json somewhere on the device and then reference inside my js file like this request.open('GET', 'file-path-to-saved-json.data-file', false);
How can I achieve this?
After working with the idea some more here is what I came up with.
When the application is installed there is a default data file in the package that I copy to the Documents folder. When the application didFinishLaunchingWithOptions runs I call the following method:
- (void)writeJsonToFile
{
//applications Documents dirctory path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//live json data url
NSString *stringURL = #"http://path-to-live-file.json";
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
//attempt to download live data
if (urlData)
{
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,#"data.json"];
[urlData writeToFile:filePath atomically:YES];
}
//copy data from initial package into the applications Documents folder
else
{
//file to write to
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,#"data.json"];
//file to copy from
NSString *json = [ [NSBundle mainBundle] pathForResource:#"data" ofType:#"json" inDirectory:#"html/data" ];
NSData *jsonData = [NSData dataWithContentsOfFile:json options:kNilOptions error:nil];
//write file to device
[jsonData writeToFile:filePath atomically:YES];
}
}
Then throughout the application when I need to reference the data, I use the saved file.
//application Documents dirctory path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSError *jsonError = nil;
NSString *jsonFilePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,#"data.json"];
NSData *jsonData = [NSData dataWithContentsOfFile:jsonFilePath options:kNilOptions error:&jsonError ];
To reference the json file in my JS code, I added a URL parameter for "src" and passed the file path to the Applications Documents folder.
request.open('GET', src, false);
I want to save an NSMutableArray or NSDictionary as a permanent file. Then, I would like to reopen the file later.
Is this possible? If so, how can I do it?
To write in file
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:FILE_NAME];
[myArray writeToFile:filePath atomically:YES];
To read from file
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:FILE_NAME];
myArray = [NSArray arrayWithContentsOfFile:filePath];
myArray will be nil if file is not present. And NSDictionary has similar methods. Please check the reference for the details of these methods.
May be you can convert a Dictionary to JSON data.and write it to a file.
NSDictionary *dict = /* the NSDictionary/NSArray you need to write */
NSError *writeError = nil;
NSData* data;
data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&writeError];
if (!writeError) {
[data writeToFile:filePath atomically:YES];
}