Getting response of weather application latitude,longitude values from server - ios

I made the coding of getting weather application response.I could not get the exact latitude,longitude and population value.Instead of exact value i am getting response as a null.After that i cant get the other response.Also the response is-> " Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSArrayM objectAtIndex:]: index 1 beyond bounds [0 .. 0]' "
Something i have done wrong in array index format.So anyone help me to get all values?
This is my coding
.M part
-(void)viewDidLoad
{
[super viewDidLoad];
NSMutableURLRequest *request =[[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:#"http://api.worldweatheronline.com/free/v1/search.ashx?query=London&num_of_results=3&format=json&key=xkq544hkar4m69qujdgujn7w"]];
[request setHTTPMethod:#"POST"];
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSDictionary *dict1 =[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&err];
//NSDictionary *dict1a =[dict1 objectForKey:#"JSON"];
NSDictionary *dict2 = [dict1 objectForKey:#"search_api"];
NSArray *array1 =[dict2 objectForKey:#"result"];
for(int i=0;i<[array1 count]; i++)
{
NSDictionary *dict3 =[array1 objectAtIndex:i];
NSArray *array2 =[dict3 objectForKey:#"areaName"];
NSDictionary *dict4 =[array2 objectAtIndex:i];
// NSArray *arr3 =[dict4 objectForKey:#"London"];
//manage.transformName= [NSString stringWithFormat:#"%#",[venueNem objectForKey:#"username"]];
NSString *str1= [NSString stringWithFormat:#"%#",[dict4 objectForKey:#"value"]];
NSLog(#"the response ==%#",str1);
NSArray *array3 =[dict3 objectForKey:#"country"];
NSDictionary *dict5 =[array3 objectAtIndex:i];
NSString *str2 =[NSString stringWithFormat:#"%#",[dict5 objectForKey:#"value"]];
NSLog(#"the response ==%#",str2);
NSString *str3 =[NSString stringWithFormat:#"%#",[dict5 objectForKey:#"latitude"]];
NSLog(#"the response ==%#",str3);
NSString *str4 =[NSString stringWithFormat:#"%#",[dict5 objectForKey:#"longitude"]];
NSLog(#"the response ==%#",str4);
NSString *str5 = [NSString stringWithFormat:#"%#",[dict5 objectForKey:#"population"]];
NSLog(#"the response ==%#",str5);
NSArray *arr4 =[dict3 objectForKey:#"region"];
NSDictionary *dict6 =[arr4 objectAtIndex:i];
NSString *str6 = [NSString stringWithFormat:#"%#",[dict6 objectForKey:#"value"]];
NSLog(#"the response ==%#",str6);
NSArray *arr5 =[dict3 objectForKey:#"weatherUrl"];
NSDictionary *dict7 =[arr5 objectAtIndex:i];
NSString *str7 =[NSString stringWithFormat:#"%#",[dict7 objectForKey:#"value"]];
NSLog(#"the response ==%#",str7);
}
for(int j=0;j<[array1 count];j++)
{
NSDictionary *dict8 =[array1 objectAtIndex:j];
NSArray *arr6 =[dict8 objectForKey:#"areaname"];
NSDictionary *dict9 =[arr6 objectAtIndex:j];
NSString *str8 =[NSString stringWithFormat:#"%#",[dict9 objectForKey:#"value"]];
NSLog(#"the response ==%#",str8);
NSArray *arr7 =[dict8 objectForKey:#"country"];
NSDictionary *dict10 =[arr7 objectAtIndex:j];
NSString *str9 =[NSString stringWithFormat:#"%#",[dict10 objectForKey:#"value"]];
NSLog(#"the response ==%#",str9);
NSString *str10 =[NSString stringWithFormat:#"%f",[dict10 objectForKey:#"latitude"]];
NSLog(#"the response ==%#",str10);
NSString *str11 =[NSString stringWithFormat:#"%f",[dict10 objectForKey:#"longitude"]];
NSLog(#"the response ==%#",str11);
NSString *str12 =[NSString stringWithFormat:#"%d",[dict10 objectForKey:#"population"]];
NSLog(#"the response ==%#",str12);
NSArray *arr8 =[dict8 objectForKey:#"region"];
NSDictionary *dict11 =[arr8 objectAtIndex:j];
NSString *str13 =[NSString stringWithFormat:#"%#",[dict11 objectForKey:#"value"]];
NSLog(#"the response ==%#",str13);
NSArray *arr9 =[dict8 objectForKey:#"weatherurl"];
NSDictionary *dict12 =[arr9 objectAtIndex:j];
NSString *str14 =[NSString stringWithFormat:#"%#",[dict12 objectForKey:#"value"]];
NSLog(#"the response ==%#",str14);
}
NSDictionary *dict13 =[array1 objectAtIndex:2];
NSArray *arr10 =[dict13 objectForKey:#"areaname"];
NSDictionary *dict14 =[arr10 objectAtIndex:2];
NSString *str15 =[NSString stringWithFormat:#"%#",[dict14 objectForKey:#"value"]];
NSLog(#"the response ==%#",str15);
NSArray *arr11 =[dict13 objectForKey:#"country"];
NSDictionary *dict15 =[arr11 objectAtIndex:2];
NSString *str16 =[NSString stringWithFormat:#"%#",[dict15 objectForKey:#"value"]];
NSLog(#"the response ==%#",str16);
NSString *str17 =[NSString stringWithFormat:#"%f",[dict15 objectForKey:#"latitude"]];
NSLog(#"the response ==%#",str17);
NSString *str18 =[NSString stringWithFormat:#"%f",[dict15 objectForKey:#"longitude"]];
NSLog(#"the response ==%#",str18);
NSString *str19 =[NSString stringWithFormat:#"%d",[dict15 objectForKey:#"population"]];
NSLog(#"the response ==%#",str19);
NSArray *arr12 =[dict13 objectForKey:#"region"];
NSDictionary *dict16 =[arr12 objectAtIndex:2];
NSString *str20 =[NSString stringWithFormat:#"%#",[dict16 objectForKey:#"value"]];
NSLog(#"the response ==%#",str20);
NSArray *arr13 =[dict13 objectForKey:#"weatherurl"];
NSDictionary *dict17 =[arr13 objectAtIndex:2];
NSString *str21 =[NSString stringWithFormat:#"%#",[dict17 objectForKey:#"value"]];
NSLog(#"the response ==%#",str21); }

Look at you first FOR loop. I am not saying the error is in only there.
EDIT
for(int i=0;i<[array1 count]; i++)
{
NSDictionary *dict3 =[array1 objectAtIndex:i];
NSArray *key = [dict3 allKeys];
for (int j = 0; j < key.count ; j++) {
if ([[key objectAtIndex:j] isEqualToString:#"areaName"]) {
NSArray *array2 =[dict3 objectForKey:#"areaName"];
//Area name
NSString *area = [[array2 objectAtIndex:0] objectForKey:#"value"];
}
else if ([[key objectAtIndex:j] isEqualToString:#"country"]){
NSArray *array2 =[dict3 objectForKey:#"country"];
//Country
NSString *country = [[array2 objectAtIndex:0] objectForKey:#"value"];
}
else if ([[key objectAtIndex:j] isEqualToString:#"latitude"]){
//Latitude
NSString *latitude = [dict3 objectForKey:#"latitude"];
}
else if ([[key objectAtIndex:j] isEqualToString:#"longitude"]){
//longitude
NSString *longitude = [dict3 objectForKey:#"longitude"];
}
else if ([[key objectAtIndex:j] isEqualToString:#"population"]){
//population
NSString *population = [dict3 objectForKey:#"population"];
}
else if ([[key objectAtIndex:j] isEqualToString:#"region"]){
NSArray *array2 =[dict3 objectForKey:#"region"];
//region
NSString *region = [[array2 objectAtIndex:0] objectForKey:#"value"];
}
else if ([[key objectAtIndex:j] isEqualToString:#"weatherUrl"]){
NSArray *array2 =[dict3 objectForKey:#"weatherUrl"];
//weatherUrl
NSString *weatherUrl = [[array2 objectAtIndex:0] objectForKey:#"value"];
}
}
}

arra=[[NSMutableArray alloc]init];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://api.worldweatheronline.com/free/v1/search.ashx?query=London&num_of_results=3&format=json&key=xkq544hkar4m69qujdgujn7w"]];
[request setHTTPMethod:#"GET"];
[request setValue:#"application/json;charset=UTF-8" forHTTPHeaderField:#"content-type"];
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err];
NSArray *array=[[jsonArray objectForKey:#"search_api"]objectForKey:#"result"];
for (int i=0; i<[array count]; i++) {
NSLog(#"the areaName==%#",[[[[array objectAtIndex:i]objectForKey:#"areaName"]objectAtIndex:0]objectForKey:#"value"]);
NSLog(#"the country==%#",[[[[array objectAtIndex:i]objectForKey:#"country"]objectAtIndex:0]objectForKey:#"value"]);
NSLog(#"the latitude==%#",[[array objectAtIndex:i]objectForKey:#"latitude"]);
NSLog(#"the long==%#",[[array objectAtIndex:i]objectForKey:#"longitude"]);
NSLog(#"the pop==%#",[[array objectAtIndex:i]objectForKey:#"population"]);
NSLog(#"the region==%#",[[[[array objectAtIndex:i]objectForKey:#"region"]objectAtIndex:0]objectForKey:#"value"]);
NSLog(#"the url==%#",[[[[array objectAtIndex:i]objectForKey:#"weatherUrl"]objectAtIndex:0]objectForKey:#"value"]);
NSString *areaName=[[[[array objectAtIndex:i]objectForKey:#"areaName"]objectAtIndex:0]objectForKey:#"value"];
[arra addObject:areaName];
}

Related

How to print the json data

I'm trying to learn JSON with IOS since I'm a beginner in IOS devices, i tried this code so far
-(void)retriveData
{
NSURL *url = [NSURL URLWithString:#"http://localhost/testjson.php"];
NSData *data = [NSData dataWithContentsOfURL:url];
json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
cities = [[NSMutableArray alloc] init];
for (int i=0; i<json.count; i++) {
NSString *cID = [[json objectAtIndex:i] objectForKey:#"id"];
NSString *cName = [[json objectAtIndex:i] objectForKey:#"CityName"];
NSString *cState = [[json objectAtIndex:i] objectForKey:#"CityState"];
NSString *cPopulation = [[json objectAtIndex:i] objectForKey:#"CityPopulation"];
NSString *cCountry = [[json objectAtIndex:i] objectForKey:#"Country"];
Country *myCity = [[Country alloc] initWithCityID:cID andCityName:cName andCityState:cState andCityPopulation:cPopulation andCityCountry:cCountry];
[cities addObject:myCity];
}
}
Anyone can show me now how i can print the data? this is the json file
[{"0":"1","id":"1","1":"Muscat","CityName":"Muscat","2":"Muscat","CityState":"Muscat","3":"25000","CityPopulation":"25000","4":"Oman","Country":"Oman"},{"0":"2","id":"2","1":"Bawsher","CityName":"Bawsher","2":"Muscat","CityState":"Muscat","3":"10000","CityPopulation":"10000","4":"Oman","Country":"Oman"},{"0":"3","id":"3","1":"AlMawalih","CityName":"AlMawalih","2":"Seeb","CityState":"Seeb","3":"5000","CityPopulation":"5000","4":"Oman","Country":"Oman"},{"0":"4","id":"4","1":"Oran","CityName":"Oran","2":"Oran","CityState":"Oran","3":"100000","CityPopulation":"100000","4":"Algeria","Country":"Algeria"},{"0":"5","id":"5","1":"Constantine","CityName":"Constantine","2":"Constantine","CityState":"Constantine","3":"150000","CityPopulation":"150000","4":"Algeria","Country":"Algeria"}]
Below is my very understandable and basic coding according to your question.It is helpful for you.
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://localhost/testjson.php"]];
[request setHTTPMethod:#"GET"];
[request setValue:#"application/json;charset=UTF-8" forHTTPHeaderField:#"content-type"];
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
//You need to check response.Once you get the response copy that and paste in ONLINE JSON VIEWER in GOOGLE.If you do this clearly you can get the correct results.
//After that it depends upon the json format whether it is DICTIONARY or ARRAY
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err];
NSLog(#"The json output array is - %#",jsonArray);
for(int i=0;i>[jsonArray count];i++)
{
NSString *strZero = [NSString stringWithFormat:#"%#",[array objectAtIndex:i]valueForKey:#"0"]];
NSLog(#"The zero is-%#",strZero);
NSString *strOne = [NSString stringWithFormat:#"%#",[array objectAtIndex:i]valueForKey:#"1"]];
NSLog(#"The One is-%#",strOne);
NSString *strTwo = [NSString stringWithFormat:#"%#",[array objectAtIndex:i]valueForKey:#"2"]];
NSLog(#"The Two is-%#",strTwo);
NSString *strThree = [NSString stringWithFormat:#"%#",[array objectAtIndex:i]valueForKey:#"3"]];
NSLog(#"The three is-%#",strThree);
NSString *strFour = [NSString stringWithFormat:#"%#",[array objectAtIndex:i]valueForKey:#"4"]];
NSLog(#"The four is-%#",strFour);
NSString *strID = [NSString stringWithFormat:#"%#",[array objectAtIndex:i]valueForKey:#"id"]];
NSLog(#"The ID is-%#",strID);
NSString *strCityName = [NSString stringWithFormat:#"%#",[array objectAtIndex:i]valueForKey:#"CityName"]];
NSLog(#"The CityName is-%#",strCityName);
NSString *strCityState = [NSString stringWithFormat:#"%#",[array objectAtIndex:i]valueForKey:#"CityState"]];
NSLog(#"The CityState is-%#",strCityState);
NSString *strCityPopulation = [NSString stringWithFormat:#"%#",[array objectAtIndex:i]valueForKey:#"CityPopulation"]];
NSLog(#"The CityPopulation is-%#",strCityPopulation);
NSString *strCountry = [NSString stringWithFormat:#"%#",[array objectAtIndex:i]valueForKey:#"Country"]];
NSLog(#"The Country is-%#",strCountry);
}
By printing you mean show the data in the console ?
Did you try this ?
NSString* str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Data: %#", str);

Parsing json from array of array

I have the json data were within the first array I main category array with name "Response" within that I have parent category array with name "0" within which I have child category array with name "0" and here is my json format
{"Response":[{"menuname":"Jewellery","menuid":"1","0":[{"catname":"Rings","catid":"1","0":[{"scatname":"Engagement Rings","scatid":"4"},{"scatname":"Wedding Rings","scatid":"5"},{"scatname":"kk","scatid":"35"}]},{"catname":"Pendants","catid":"2","0":[{"scatname":"Office Wear","scatid":"8"}]},{"catname":"Bracelets","catid":"3","0":[{"scatname":"Studded","scatid":"9"}]},{"catname":"Earrings","catid":"6","0":[{"scatname":"Ethnic Jhumkas","scatid":"7"}]},{"catname":"Chain's","catid":"33","0":[]},{"catname":"Jewel","catid":"34","0":[]}]},{"menuname":"Collections","menuid":"2","0":[{"catname":"SOUND OF LOVE","catid":"15","0":[{"scatname":"LOVE BRACELET","scatid":"16"}]},{"catname":"COLORFUL AFFAIR","catid":"17","0":[{"scatname":"Passion ring","scatid":"18"}]},{"catname":"Evermore Collection","catid":"19","0":[]},{"catname":"BOARDROOM GLAM ","catid":"20","0":[]},{"catname":"ETERNAL GOLD","catid":"21","0":[]},{"catname":"FASHIONISTA COLLECTION","catid":"22","0":[]}]},{"menuname":"Gold Coin","menuid":"3","0":[{"catname":"SOUND OF LOVE","catid":"15","0":[{"scatname":"LOVE BRACELET","scatid":"16"}]},{"catname":"COLORFUL AFFAIR","catid":"17","0":[{"scatname":"Passion ring","scatid":"18"}]},{"catname":"Evermore Collection","catid":"19","0":[]},{"catname":"BOARDROOM GLAM ","catid":"20","0":[]},{"catname":"ETERNAL GOLD","catid":"21","0":[]},{"catname":"FASHIONISTA COLLECTION","catid":"22","0":[]}]},{"menuname":"OFF THE SHELF","menuid":"4","0":[{"catname":"testing from pixel","catid":"13","0":[]},{"catname":"New pixel","catid":"23","0":[]},{"catname":"Evermore Collection","catid":"19","0":[]},{"catname":"BOARDROOM GLAM ","catid":"20","0":[]},{"catname":"ETERNAL GOLD","catid":"21","0":[]},{"catname":"FASHIONISTA COLLECTION","catid":"22","0":[]}]}]}
and I want to display in expandable tableview as below
Jewellery
Rings
Engagement Rings
Wedding Rings
kk
Pendants
Ofice Wear
Collections
Sound Of Love
Love bracelet
Colorful Affair
Passion ring
Here is the code I used in viewdidLoad
NSDictionary *pJson;
NSMutableString *postStr = [NSMutableString stringWithString:kURL];
[postStr appendString:[NSString stringWithFormat:#"?tag=%#&id=%#",kCategoryFilter,kPrecious]];
[postStr setString:[postStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:postStr]];
NSLog(#"%#",postStr);
[request setHTTPMethod:#"POST"];
_connection = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES];
NSURL *url = [NSURL URLWithString:postStr];
NSData *data = [NSData dataWithContentsOfURL:url];
pJson = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSLog(#"%#",pJson);
NSMutableArray *arr = [pJson objectForKey:#"Response"];
NSLog(#"%lu",(unsigned long)arr.count);
NSMutableDictionary *dict2 =[[NSMutableDictionary alloc]init];// [arr objectAtIndex:NSIndexPath.row];
[dict2 setObject:arr forKey:#"dictionary1"];
dict2 = [arr objectAtIndex:0];
NSArray *arr1 =[dict2 objectForKey:#"0"];
NSLog(#"%lu",(unsigned long)arr1.count);
NSUInteger y;
for (int i=0;i<arr.count;i++) {
NSString *ring_data = [[arr objectAtIndex:i]objectForKey:#"menuname"];
NSString *id_data = [[arr objectAtIndex:i]objectForKey:#"menuid"];
NSLog(#"AUTHOR: %#",ring_data);
NSLog(#"%#",id_data);
dictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:
ring_data,#"menuname",id_data,#"menuId",nil];
[myObject addObject:dictionary];
NSMutableArray *arr1 = [dict2 objectForKey:#"0"];
NSLog(#"%lu",(unsigned long)arr1.count);
y = arr.count;
for (NSUInteger i=0;i<arr1.count;i++) {
NSArray *count = [[[arr1 objectAtIndex:i] objectForKey:arr]valueForKey:#"catname"];
NSString *myCount = [NSString stringWithFormat:#"%lu",(unsigned long)[count count]];
NSString *ring_data = [[arr1 objectAtIndex:i]objectForKey:#"catname"];
NSLog(#"AUTHOR: %#",ring_data);
// NSLog(#"%#",catname_data);
dictionary1 = [NSMutableDictionary dictionaryWithObjectsAndKeys:
ring_data,#"catname",
nil];
[myObject1 addObject:dictionary1];
}
}
I tried some coding for you.Follow that code and customize where you want to add to array and where to set dictionary.
NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err];
NSArray *array=[jsonArray objectForKey:#"Response"];
for (int i=0;i<[array count];i++)
{
NSMutableDictionary *dict = [array objectAtIndex:i];
NSMutableArray *arrayDictValue = [dict valueForKey:[NSString stringWithFormat:#"%d",0]];
NSString *strMenuName = [NSString stringWithFormat:#"%#",[arrayDictValue valueForKey:#"menuname"]];
NSString *strMenuID = [NSString stringWithFormat:#"%#",[arrayDictValue valueForKey:#"menuid"]];
NSLog(#"The strMenuName is-%#",strMenuName);
NSLog(#"The strMenuID is-%#",strMenuID);
for (int j=0; j<[arrayDictValue count]; i++)
{
NSMutableDictionary *dictInside = [arrayDictValue objectAtIndex:j];
NSArray *arrayInsideDict = [dictInside valueForKey:#"0"];
for (int k =0; k<[arrayInsideDict count]; i++)
{
NSString *strCatName = [NSString stringWithFormat:#"%#",[[arrayInsideDict objectAtIndex:k ]valueForKey:#"catname"]];
NSString *strCatID = [NSString stringWithFormat:#"%#",[[arrayInsideDict objectAtIndex:k ]valueForKey:#"catid"]];
NSLog(#"The strCateName is-%#",strCatName);
NSLog(#"The strCatID is-%#",strCatID);
NSMutableDictionary *dictInArray = [[arrayInsideDict objectAtIndex:0] valueForKey:#"0"];
NSString *strSCatName = [NSString stringWithFormat:#"%#",[dictInArray valueForKey:#"scatname"]];
NSString *strSCatID = [NSString stringWithFormat:#"%#",[dictInArray valueForKey:#"scatid"]];
NSLog(#"the strSCatName is - %#",strSCatName);
NSLog(#"the strSCatID is - %#",strSCatID);
}
}
}

Parse NSString to NSArray

I am trying to parse an NSString to NSArray but couldn't get any success. Here is my String: NSString *points = #"[[51.471914582, -0.12274114637],[51.47287707533, -0.12163608379]]";
I want this string mapped to NSArray.
NSArray *tempArray = points;
OK, code golf (untested):
NSString *points = #"[[51.471914582, -0.12274114637],[51.47287707533, -0.12163608379]]";
NSError *error = nil;
NSArray *pointsArray = [NSJSONSerialization JSONObjectWithData:[points dataUsingEncoding:NSUTF8StringEncoding]
options:kNilOptions
error:&error];
for (NSArray *point in pointsArray) {
NSAssert([point count] == 2, #"Invalid point");
// do thing with point
CGPoint pt = CGPointMake([point[0] floatValue], [point[1] floatValue]);
}
Can you plz try this, May it solve your problem,
NSString *points = #"[[51.471914582, -0.12274114637],[51.47287707533, -0.12163608379]]";
NSArray* arrayOfStrings = [points componentsSeparatedByString:#","];
NSLog(#"%#",arrayOfStrings);
NSMutableArray *copyArray = [arrayOfStrings mutableCopy];
NSMutableString *stringFirst = (NSMutableString *)[copyArray objectAtIndex:0];
NSMutableString *stringLast = (NSMutableString *)[copyArray lastObject];
stringFirst=[stringFirst substringFromIndex:1];
stringLast=[stringLast substringToIndex:stringLast.length-1];
[copyArray replaceObjectAtIndex:0 withObject:stringFirst];
[copyArray replaceObjectAtIndex:(copyArray.count-1) withObject:stringLast];
NSMutableArray *yourarray = [[NSMutableArray alloc] init];
for (int i=0; i<=(copyArray.count/2); i+=2) {
[yourarray addObject:[NSString stringWithFormat:#"%#,%#",[copyArray objectAtIndex:i], [copyArray objectAtIndex:i+1]]];
}
NSLog(#"%#",yourarray);
Happy Coding!!
That string looks like JSON so you can use NSJSONSerialization
NSData * data = [points dataUsingEncoding: NSUTF8StringEncoding];
NSError * error = nil;
NSArray * arrayOfPointArrays = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];

Need help in trying to read and write from plist

I am trying to save an NSMutable Array and NSString into plist and then if it exists initialize the value from plist. However when I re run the app, the values do not get initialize as it is suppose to. So far the following is what I have.
if (self = [super init]) {
NSString *path=[self getFileUrl];
NSFileManager *fm = [[NSFileManager alloc] init];
if ([fm fileExistsAtPath:path]) {
_history = [d objectForKey:#"stringKey"];
class=[d objectForKey: #"ArrayKey"];
}
NSDictionary *d;
However the values are not getting initialized as per the plist. Is it the way I am extracting the values from the dictionary?
here is my function that saving json into plist in nscachesdirectory
-(void)saveproducts{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString* plistPath = [documentsPath stringByAppendingPathComponent:#"Products.plist"];
NSDictionary*dict = [NSDictionary dictionary];
NSMutableArray *types = [NSMutableArray array];
NSArray *dictArray = [NSArray array];
NSArray *dictKeys = [NSArray array];
NSArray *productObjects = [NSArray array];
NSArray *productKeys = [NSArray array];
for (int i=0; i<appDelegate.products.count; i++) {
NSMutableArray *tmpProds = [NSMutableArray array];
NSString *t_ID = [[appDelegate.products objectAtIndex:i] valueForKey:#"id"];
NSString *t_image = [[appDelegate.products objectAtIndex:i] valueForKey:#"image"];
NSString *t_name =[[appDelegate.products objectAtIndex:i] valueForKey:#"name"];
NSArray *products = [[appDelegate.products objectAtIndex:i] valueForKey:#"products"];
NSDictionary *productsDict = [NSDictionary dictionary];
for (int j=0; j<products.count; j++) {
NSString *p_id = [[products objectAtIndex:j] valueForKey:#"id"];
NSString *p_name = [[products objectAtIndex:j] valueForKey:#"name"];
NSString *p_name2 = [[products objectAtIndex:j] valueForKey:#"name2"];
NSString *image = [[products objectAtIndex:j] valueForKey:#"image"];
NSString *typeID = [[products objectAtIndex:j] valueForKey:#"type_id"];
NSString *active = [[products objectAtIndex:j] valueForKey:#"active"];
NSString *available = [[products objectAtIndex:j] valueForKey:#"available"];
NSString *desc = [[products objectAtIndex:j] valueForKey:#"description"];
NSString *price = [[products objectAtIndex:j] valueForKey:#"price"];
if ([p_name2 isEqual:[NSNull null]]) {
p_name2 =#"undefined";
}
if ([desc isEqual:[NSNull null]]) {
desc = #"";
}
productObjects = [NSArray arrayWithObjects:p_id,p_name,p_name2,image,typeID,active,available,desc,price, nil];
productKeys = [NSArray arrayWithObjects:#"id",#"name",#"name2",#"image",#"type_id",#"active",#"available",#"desc",#"price", nil];
productsDict = [NSDictionary dictionaryWithObjects:productObjects forKeys:productKeys];
[tmpProds addObject:productsDict];
if (![image isEqualToString:#""]) {
[foodImages addObject:image];
}
}
dictArray = [NSArray arrayWithObjects:t_ID,t_image,t_name,tmpProds, nil];
dictKeys = [NSArray arrayWithObjects:#"id",#"image",#"name",#"products", nil];
dict = [NSDictionary dictionaryWithObjects:dictArray forKeys:dictKeys];
[types addObject:dict];
}
NSDictionary* plistDict = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects:types, nil] forKeys:[NSArray arrayWithObjects:#"ptype", nil]];
NSString *error = nil;
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
if(plistData)
{
[plistData writeToFile:plistPath atomically:YES];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setBool:YES forKey:#"cached"];
[defaults synchronize];
}
else
{
NSLog(#"Error log: %#", error);
}
}
and this one reading plist
-(void)loadFromplist{
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString* plistPath = [documentsPath stringByAppendingPathComponent:#"Products.plist"];
NSData *plistData = [[NSFileManager defaultManager] contentsAtPath:plistPath];
NSDictionary *dict = (NSDictionary*)[NSPropertyListSerialization propertyListFromData:plistData mutabilityOption:NSPropertyListMutableContainersAndLeaves format:nil errorDescription:nil];
productsArray = [dict valueForKey:#"ptype"];
[self.tableView reloadData];
}

how to optimize this code using for loop

can some pne please help me in optimize this code:
- (NSMutableDictionary *) parseResponse:(NSData *) data {
NSString *myData = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
NSLog(#"JSON data = %#", myData);
NSError *jsonParsingError = nil;
//parsing the JSON response
id jsonObject = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:&jsonParsingError];
if (jsonObject != nil && jsonParsingError == nil)
{
//NSLog(#"Successfully deserialized...");
NSLog(#"json object is %#",jsonObject);
if([jsonObject isKindOfClass:[NSDictionary class]])
{
NSLog(#"It has only dictionary so simply read it");
}
else if([jsonObject isKindOfClass:[NSArray class]])
{
NSLog(#"It has only NSArray so simply read it");
}
else if([jsonObject isKindOfClass:[NSString class]])
{
NSString *stringWithoutOpenCurly = [jsonObject stringByReplacingOccurrencesOfString:#"{" withString:#""];
NSString *stringWithoutOpenAndCloseCurly = [stringWithoutOpenCurly stringByReplacingOccurrencesOfString:#"}" withString:#""];
NSArray *arrayOfKeyValue = [stringWithoutOpenAndCloseCurly componentsSeparatedByString:#","];
NSString *statusString = [arrayOfKeyValue objectAtIndex:0];
NSArray *statusKeyValueArray = [statusString componentsSeparatedByString:#":"];
NSString *statusKey, *statusValue;
statusKey = [[statusKeyValueArray objectAtIndex:0] stringByReplacingOccurrencesOfString:#"\"" withString:#""];
statusValue = [[statusKeyValueArray objectAtIndex:1] stringByReplacingOccurrencesOfString:#"\"" withString:#""];
NSString *messageString = [arrayOfKeyValue objectAtIndex:1];
NSArray *messageKeyValueArray = [messageString componentsSeparatedByString:#":"];
NSString *messageKey, *messageValue;
messageKey = [[messageKeyValueArray objectAtIndex:0] stringByReplacingOccurrencesOfString:#"\"" withString:#""];
messageValue = [[messageKeyValueArray objectAtIndex:1] stringByReplacingOccurrencesOfString:#"\"" withString:#""];
NSString *dataIdString = [arrayOfKeyValue objectAtIndex:2];
NSArray *dataIdKeyValueArray = [dataIdString componentsSeparatedByString:#":"];
NSString *dataIdKey, *dataIdValue;
dataIdKey = [[dataIdKeyValueArray objectAtIndex:0] stringByReplacingOccurrencesOfString:#"\"" withString:#""];
dataIdValue = [[dataIdKeyValueArray objectAtIndex:1] stringByReplacingOccurrencesOfString:#"\"" withString:#""];
NSString *nextString = [arrayOfKeyValue objectAtIndex:3];
NSArray *nextKeyValueArray = [nextString componentsSeparatedByString:#":"];
NSString *nextKey, *nextValue;
nextKey = [[nextKeyValueArray objectAtIndex:0] stringByReplacingOccurrencesOfString:#"\"" withString:#""];
nextValue = [[nextKeyValueArray objectAtIndex:1] stringByReplacingOccurrencesOfString:#"\"" withString:#""];
NSString *b64String = [arrayOfKeyValue objectAtIndex:4];
NSArray *b64KeyValueArray = [b64String componentsSeparatedByString:#":"];
NSString *b64Key, *b64Value;
b64Key = [[b64KeyValueArray objectAtIndex:0] stringByReplacingOccurrencesOfString:#"\"" withString:#""];
b64Value = [[b64KeyValueArray objectAtIndex:1] stringByReplacingOccurrencesOfString:#"\"" withString:#""];
NSString *fileNameString = [arrayOfKeyValue objectAtIndex:5];
NSArray *fileNameKeyValueArray = [fileNameString componentsSeparatedByString:#":"];
NSString *fileNameKey, *fileNameValue;
fileNameKey = [[fileNameKeyValueArray objectAtIndex:0] stringByReplacingOccurrencesOfString:#"\"" withString:#""];
fileNameValue = [[fileNameKeyValueArray objectAtIndex:1] stringByReplacingOccurrencesOfString:#"\"" withString:#""];
NSMutableDictionary *responseDictionary = [NSMutableDictionary dictionaryWithObjects:[NSArray arrayWithObjects:statusValue, messageValue, dataIdValue, nextValue, b64Value, fileNameValue, nil] forKeys:[NSArray arrayWithObjects:statusKey, messageKey, dataIdKey, nextKey, b64Key, fileNameKey, nil]];
NSLog(#"manually created dictionary is ++++++++++++++++++++++++++++++%#",responseDictionary);
NSLog(#"statusValue is ++++++++++++++++++++++++++++++%#",[responseDictionary valueForKey:statusKey]);
return responseDictionary;
}
}
else //previoucly no else handler so put it here
{
// mErrorMessage = #"Server Error";
// [self stopIndicatorProgressWithError];
}
}
jsonObject is true for NSString class only???? do not know what's problem.
Any Help?
thanks & regards.
You can "optimize" your code by using the appropriate Foundation classes:
NSString *jsonObject = ...; // your JSON data as string
NSData *jsonData = [jsonObject dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSDictionary * responseDictionary = [NSJSONSerialization JSONObjectWithData:jsonData
options:0 error:&error];
or, if you really need a mutable dictionary:
NSMutableDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingMutableContainers error:&error];

Resources