How to access a json file locally from within the app - iphone

I'm trying to figure out how to access a json file locally, from within the app. Currently I've been using the json file remotely from a server like this:
jsonStringCategory = #"http://****categories?country=us";
}
// Download the JSON file
NSString *jsonString = [NSString
stringWithContentsOfURL:[NSURL URLWithString:jsonStringCategory]
encoding:NSStringEncodingConversionAllowLossy|NSUTF8StringEncoding
error:nil];
NSLog(#"jsonStringCategory is %#", jsonStringCategory);
NSMutableArray *itemsTMP = [[NSMutableArray alloc] init];
// Create parser
SBJSON *parser = [[SBJSON alloc] init];
NSDictionary *results = [parser objectWithString:jsonString error:nil];
itemsTMP = [results objectForKey:#"results"];
self.arForTable = [itemsTMP copy];
[self.tableView reloadData];
I tried this:
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"categoriesus" ofType:#"json"];
jsonStringCategory = [[NSString alloc] initWithContentsOfFile:filePath];
thanks

NSString *filePath = [[NSBundle mainBundle] pathForResource:#"filename" ofType:#"json"];
NSData *jsonData = [NSData dataWithContentsOfFile:filePath];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:nil];

Could you be more specific? which file do you try to access? did you already save it?
1/ For your main problem: you can create a dictionnary or array with a file path
[NSDictionary dictionaryWithContentsOfFile:<#(NSString *)#>]
[NSArray arrayWithContentsOfFile:<#(NSString *)#>]
2/ But you can, as you wrote it, read the "string" content from a file and then, eventually, parse it. For that you need (for example) a path like this (for the "directory" dir, could be the "cache" dir)
NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *pathToFile = [ [ [ [ array objectAtIndex:0 ] stringByAppendingPathComponent:#"nameOfTheFile" ] stringByAppendingString:#".ext" ] retain ];
And then use "pathToFile" in my 1/ example.
3/ For your internet access, I recommend you to check AFNetworking. It's better to do async download ;-) (yours is synchronous)
https://github.com/AFNetworking/AFNetworking

I like to use CoreData. Follow those steps:
1-)First of all create a model, and add attribute String type with name jsonvalue.
2-)create this function to save your json file:
-(void)saveJson:(NSString*)d
{
NSString * data = [d retain];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:#"NameObjectModel" inManagedObjectContext:context]];
NSError *error = nil;
NSArray *results = [context executeFetchRequest:request error:&error];
[request release];
// error handling code
if(error){
}
else{
Session* favoritsGrabbed = [results objectAtIndex:0];
favoritsGrabbed.jsonvalue = data;
}
if(![context save:&error]){
NSLog(#"data saved.");
}
}
3-)create a function to load your json:
-(void)loadJSONFromFile
{
//Recover data from core data.
// Define our table/entity to use
NSEntityDescription *entity = [NSEntityDescription entityForName:#"NameObjectModel" inManagedObjectContext:context];
// Setup the fetch request
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entity];
// Define how we will sort the records - atributo que sera recuperado
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"jsonvalue" ascending:NO];
NSArray *sortDescriptors = [NSArray arrayWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
[sortDescriptor release];
// Fetch the records and handle an error
NSError *error;
NSMutableArray *mutableFetchResults = [[NSMutableArray alloc]initWithArray:[context executeFetchRequest:request error:&error]];
if (!mutableFetchResults) {
// Handle the error.
// This is a serious error and should advise the user to restart the application
}
if(mutableFetchResults.count == 0)
{
NSLog(#"the archive is null");
}
else if(mutableFetchResults.count > 0)
{
NameObjectModel *entity = [mutableFetchResults objectAtIndex:0];
//NSLog(#"%#",[[entity jsonvalue] JSONValue]);
NSDictionary * aux = [[entity jsonvalue] JSONValue];
if([entity jsonvalue]== nil)
{
NSLog(#"json is nil");
NSLog(#"the archive exists but json is nil");
}
else {
// set current json data cache
[self setJsonCache:aux]; // add to recovery list
}
}
[mutableFetchResults release];
[request release];
}
Don't forget: NameObjectModel = Name of your NSManagedObject.

Related

Break String that came from Json

I have a String that I got from a webserver which came in json format, but the string is huge with everything in it. I tried using the NSDICTIONARY but to no success. I was wondering what would be the best approach to break this string and add to different strings and eventually put it all in a class of strings. Thanks for the help! Here is my code:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:#"http://mym2webdesign.com/meiplay/paulsuckedabuffalo/artists.php"]];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; //Or async request
returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSError *error=nil;
NSLog(#"HHHHHHHHHHHHHH"); //use this to know how far Im getting
NSLog(returnString); // Look at the console and you can see what the restults are
/*NSDictionary *results = [returnString JSONValue];
NSString *ID = [results objectForKey:#"ID"]; // for example
NSLog(#"ID Number: %#", ID);*/
Here is some of the log i get:
[{"ID":"1","name":"kevin","bio":"kevins bio"},{"ID":"1","name":"kevin","age":"20"},{"ID":"2","name":"Cesar","bio":"Cesar bio"},{"ID":"2","name":"Cesar","age":"19"},{"ID":"3", "name":"Katherine", "bio":"Katherines bio"},{"ID":"3", "name":"Katherine", "age":"22"}]
You are doing it wrong. Its a NSArray of NSDictionaries. So first you need to assign it to NSArray and then loop over it to get each individual NSDictionary. See below.
NSArray *results = [returnString JSONValue];
for(NSDictionary *record in results)
{
NSLog(#"ID: %#", [record objectForKey:#"ID"]);
}
You'll probably be better off just using NSJSONSerialization if your app is targeted for at or over iOS 5.0:
NSArray *JSONArray = [NSJSONSerialization JSONObjectWithData:returnData options:0 error:&error];
You might need to experiment with using NSArray vs. NSDictionary, etc., but this should be an overall simpler solution.
Try this :
NSArray *results = [returnString JSONValue];
for (int i=0; i<[results count];i++) {
NSDictionary *DetailDictonary=[results objectAtIndex:i];
NSString *strid=[DetailDictonary objectForKey:#"ID"];
NSString *strName=[DetailDictonary objectForKey:#"name"];
NSString *strBio=[DetailDictonary objectForKey:#"bio"];
// Or You can set it in Your ClassFile
MyClass *classObj=[[MyClass alloc] init];
classObj.strid=[DetailDictonary objectForKey:#"ID"];
classObj.strName=[DetailDictonary objectForKey:#"name"];
classObj.strBio=[DetailDictonary objectForKey:#"bio"];
[YourMainArray addObject:classObj]; //set YourClass to Array
[classObj release];
}

Import csv file into SQLite

I have a database in SQLite, and a table named xyz which is empty. I want to import data from a csv file into that table.
Now, when I try to import csv file, it is asking me to import it into the main table, but I want to import the data into my xyz table.
How can I do that?
You can do as this way,
First you need to add your csv file in bundle.
Then you can call this method where you want to add data in database from csv
-(void)loadCSVData{
NSString *path1=[[NSString alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"YOUR_CSV_FILENAME" ofType:#"csv"] usedEncoding:&encoding error:nil];
NSArray *messArr=[path1 componentsSeparatedByString:#"\n"];
if(messArr)
{
for(int i=1;i<=[messArr count]-2;i++)
{
NSMutableDictionary *d=[[NSMutableDictionary alloc] init];
NSString *StrValue=[NSString stringWithFormat:#"%#",[messArr objectAtIndex:i]];
StrValue=[StrValue stringByReplacingOccurrencesOfString:#"\"" withString:#""];
StrValue=[StrValue stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
// Here give whatever saperator you need to saperate data
NSArray *arr=[StrValue componentsSeparatedByString:#","];
[d setValue:[arr objectAtIndex:0] forKey:#"YOUR_TABLE_FIELD_1"];
[d setValue:[arr objectAtIndex:1] forKey:#"YOUR_TABLE_FIELD_2"];
[d setValue:[arr objectAtIndex:2] forKey:#"YOUR_TABLE_FIELD_3"];
//Here add logic to insert row in your database table
}
}
i done with below code you need to just impliment that:-
-(void)restore{
#try {
NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:#"%#%#?userid=%#",kHOSTPATH,kCSVLIST,[[cntrAppDelegate setServerDetails] valueForKey:#"kUSERID"]]];
NSMutableURLRequest *requestMutable = [[NSMutableURLRequest alloc] init];
[requestMutable setURL:url];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:requestMutable returningResponse:&response error:&error];
NSLog(#"Response code: %d", [response statusCode]);
if ([response statusCode] >=200 && [response statusCode] <300)
{
NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"Response ==> %#", responseData);
SBJsonParser *jsonParser = [SBJsonParser new];
NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];
NSLog(#"--------=========%#============-------------",jsonData);
NSDictionary *dic = [jsonData objectForKey:#"Root"];
NSLog(#"---------------------ROOT VALUE IS %#",dic);
NSLog(#"----------------COUNT IS %d",[dic count]);
for (int i = 0; i < [dic count]; i++)
{
NSString *str = [[dic valueForKey:#"CSV_File"]objectAtIndex:i];
NSLog(#"STR IS %#",str);
[self.arrListOfCSV addObject:str];
}
if ([jsonData valueForKey:#"Root"] == 0)
{
}
else
{
}
}
You should better import data in Linux. And in Disk Operation System after into the SQLite,enter
separator",";
importchoose your csv pathxyz. When you create table named xyz, the name should be agree with your csv files .

Iphone sdk, memory leak

im new with objective-c. I have problem with memory leaking when developing iphone app. Leaking utility in Xcode shows that leaking problem with 'combArr'->'results' object. There is my function which parsing json from url and returns NSArray:
- (NSArray *)getListing2:(NSString *)item
from:(int)country {
//sending post request with some params
NSString *post = [#"product=" stringByAppendingString:item];
NSString *countryStr = [NSString stringWithFormat:#"&country=%d", country];
post = [post stringByAppendingString:countryStr];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *url = [prefs objectForKey:#"urlToApi"];
url = [url stringByAppendingString:#"/get-items/"];
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
[request release];
//receiving json
NSString *jsonString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
SBJsonParser *json = [[SBJsonParser alloc] init];
NSError *error = nil;
//parsing json to nsdictionary
NSDictionary *results = [[NSDictionary alloc] initWithDictionary:[json objectWithString:jsonString error:&error]];
[json release];
[jsonString release];
//generate array of items
NSMutableArray *listOfItems = [[NSMutableArray alloc] init];
for (int i = 0; i < [[results objectForKey:#"data"] count]; i++) {
[listOfItems addObject:[[results objectForKey:#"data"] objectForKey:[NSString stringWithFormat:#"%d", i]]];
}
//saving items array and count info object into one array
NSArray * returnArr = [[[NSArray arrayWithObjects:listOfItems, [results valueForKey:#"count_info"], nil] retain] autorelease];
[listOfItems release];
[results release];
return returnArr;
}
And i executing this function here:
myApi *itemsApi = [[myApi alloc] init];
NSArray *combArr = [[izdApi getListing2:item from:countryId] retain];
[itemsApi release];
listOfItems = [[combArr objectAtIndex:0] retain];
if([listOfItems count] > 0){
priceArr = [[combArr objectAtIndex:1] retain];
}
else{
totalCount = 0;
}
[combArr release];
Thank you for helping
Every time you allocate memory, you must release it. (alloc, copy, retain).
You are releasing myApi, not itemsApi. Try this...
myApi *itemsApi = [[itemsApi alloc] init];
NSArray *combArr = [[izdApi getListing2:item from:countryId] retain];
[itemsApi release];
listOfItems = [[combArr objectAtIndex:0] retain];
if([listOfItems count] > 0){
priceArr = [[combArr objectAtIndex:1] retain];
}
else{
totalCount = 0;
}
[combArr release];
If you are using Xcode 4, Try turning on ARC. In short, ARC handles the releasing of all memory. A little burden off your shoulders and one less thing for you to worry about.

How to read the JSON value on console in iphone

i have the following json value in console:
{"TokenID":"kuiHigen21","isError":false,"ErrorMessage":"","Result":[{"UserId":"153","FirstName":"Rocky","LastName":"Yadav","Email":"rocky#itg.com","ProfileImage":null,"ThumbnailImage":null,"DeviceInfoId":"12"}],"ErrorCode":900}
this is my server api :#"http://192.168.0.68:91/JourneyMapperAPI?RequestType=Login"
//api takes 5 parameters .
when i post data to server api values are posted to server and i get the above response in json format.
i want to parse the above the JSON value that i get in the response and save in sqlite database.
i am doing this code to parse the above JSON value:
-(void)connectionDidFinishLoadingNSURLConnection *)connection
{
NSString *loginStatus = [[NSString alloc] initWithBytes: [webData mutableBytes] lengthwebData length] encoding:NSUTF8StringEncoding];
NSLog(#"%#",loginStatus);
self.webData = nil;
SBJSON *parser =[[SBJSON alloc]init];
NSURLRequest *request = [NSURLRequest requestWithURLNSURL URLWithString"http://192.168.0.68:91/JourneyMapperAPI?RequestType=Login.json"]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
//NSDictionary *object = [parser objectWithString:json_string error:nil];
// parse the JSON response into an object
// Here we're using NSArray since we're parsing an array of JSON status objects
NSArray *statuses = [parser objectWithString:json_string error:nil];
for (NSDictionary *status in statuses)
{
// You can retrieve individual values using objectForKey on the status NSDictionary
// This will print the tweet and username to the console
NSLog(#"%# - %#", [status objectForKey"Login"],[status objectForKey"LoginKey"]);
[connection release]; [webData release];
}
You should check out some of the JSON parsers, my personal favourite is json-framework. After you've included one of them in your project, where you've got your JSON response from your server:
// Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSDictionary *result = [json_string JSONValue];
NSArray *statuses = [result objectForKey:#"Result"];
which will return your array of results (where each object in the array is an NSDictionary).
You can save this to a database with the help of a model class, Result
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSDictionary *result = [json_string JSONValue];
NSArray *values = [result objectForKey:#"Result"];
NSMutableArray *results = [[NSMutableArray alloc] init];
for (int index = 0; index<[values count]; index++) {
NSMutableDictionary * value = [values objectAtIndex:index];
Result * result = [[Result alloc] init];
result.UserId = [value objectForKey:#"UserId"];
result. FirstName = [value objectForKey:#"FirstName"];
...
[results addObject:result];
[result release];
}
use the array of results to save it to the database.
for (int index = 0; index<[results count]; index++) {
Result * result = [results objectAtIndex:index];
//save the object variables to database here
}

Certain JSON requests crach on adHoc, but not on debug

I am using json-framework for communication purposes with certain web service. So far it has served me well. However, this code crashes my adHoc app on the device. The same app in debug mode on the device works ok.
Here is my JSON request(that is where it crashes):
//Make values dictionary
NSMutableDictionary *valuesDictionary;
NSMutableDictionary *valuesDictionary_1;
NSMutableArray *tempArray;
NSMutableArray *values = [[NSMutableArray alloc] init];;
NSEnumerator * enumerator = [self.contactsTempArray objectEnumerator];
id tempObj;
while ( tempObj = [enumerator nextObject] ) {
valuesDictionary = [[NSMutableDictionary alloc] init];
valuesDictionary_1 = [[NSMutableDictionary alloc] init];
tempArray = [[NSMutableArray alloc] init];
//NSString *key = [NSString stringWithFormat:]
if([[tempObj objectForKey:#"Checked"] isEqualToString:#"1"]) {
[valuesDictionary setObject:[NSNumber numberWithInt:[[tempObj objectForKey:#"NotificationContactId"] intValue]] forKey:#"ContactId"];
[valuesDictionary setObject:[NSNumber numberWithBool:true] forKey:#"IsEnabled"];
}
else {
[valuesDictionary setObject:[NSNumber numberWithInt:[[tempObj objectForKey:#"NotificationContactId"] intValue]] forKey:#"ContactId"];
[valuesDictionary setObject:[NSNumber numberWithBool:false] forKey:#"IsEnabled"];
}
[tempArray addObject:valuesDictionary];
[tempArray addObject:valuesDictionary_1];
[values addObject:valuesDictionary];
[valuesDictionary release];
}
//UPDATE NOTIFICATIONS SETTINGS
//JSON POST request
NSArray *keys = [NSArray arrayWithObjects:#"sessionId", #"apiKey", #"deviceToken", #"values", nil];
NSArray *objects = [NSArray arrayWithObjects:appDelegate.sessionId, appDelegate.apiKey, appDelegate.deviceToken, values, nil];
NSDictionary *getAllSensorsDict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSString *requestString = [NSString stringWithFormat:#"%#", [getAllSensorsDict JSONFragment], nil];
NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: #"https://xxxxxxxxx"]];
[request setValue:#"application/json;charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod: #"POST"];
[request setHTTPBody: requestData];
//JSON response
NSData *jsonData = [ NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil ];
any ideas what am I doing wrong?
Is the JSON request too complex for adHoc?
Connect your iphone to your mac. Then open xcode, open menu, window, organizer. There go to "crash logs" and look the info about the crash....
Or you can even test your app in your iphone (connected to the mac) using the Build and Go button. You will see the crash messages in the console.