I am trying to populate a tableView with objects received from a JSON request.
This is my viewDidLoad method:
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog (#"HE ENTRADO EN HISTORIAL VC");
myObject = [[NSMutableArray alloc] init];
NSURL *apiURL = [NSURL URLWithString:
[NSString stringWithFormat:#"http://.. HIDDEN HERE.. /?client=%#&date=%#", #"1",#"2015-3-16"]];
NSURLRequest *request = [NSURLRequest requestWithURL:apiURL];
NSLog (#"HE MANDADO LA REQUEST DEL HISTORIAL");
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if(data.length) {
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if(responseString && responseString.length) {
NSLog(#"dATOS RECIBIDOS EN HISTORIAL=%#", responseString);
NSLog (#"HE RECIBIDO LA REQUEST DEL HISTORIAL");
NSError *jsonError;
NSData *objectData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&jsonError];
NSArray *messageArray = [json objectForKey:#"objects"];
historialServicios = [[NSMutableArray alloc]init];
// Parse and loop through the JSON
for (dictionary in messageArray) {
//datos de nivel objects
NSString * code = [dictionary objectForKey:#"code"];
NSString * date = [dictionary objectForKey:#"date"];
//datos de nivel client
NSDictionary *level2Dict = [dictionary objectForKey:#"client"];
id someObject = [level2Dict objectForKey:#"email"];
NSLog(#"ANTES DE ANADIR OBJETOS");
[historialServicios addObject:#{#"code": code, #"date": date, #"email":someObject}];
NSLog(#"DESPUES DE ANADIR OBJETOS");
NSLog(#"NOMBRE===%#",someObject);
NSString * email = someObject;
NSLog(#"EMAIL=%#",email);
NSLog(#"CODE=%#",code);
NSLog(#"DATE=%#",date);
//insertamos objetos en diccionario historialServicios
}
NSLog(#"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++SERVICIOS RECIBIDOS=%#", historialServicios);
}
}
}];
NSLog(#"NUMERO DE ITEMS=%lu", (unsigned long)[historialServicios count]);
[self.tableView reloadData];
}
The last NSLog doesn't appear in the log console. The content of the NSMutableArray are shown in the console:
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++SERVICIOS RECIBIDOS=(
{
code = SV1000000103;
date = "2015-03-18";
email = "jose#gmail.com";
},
{
code = SV1000000113;
date = "2015-03-18";
email = "jose#gmail.com";
},
{
code = SV1000000104;
date = "2015-03-16";
email = "jose#gmail.com";
},
...
But nothing is shown on the table.
Here the tableView methods:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return historialServicios.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
NSString *email = [[historialServicios objectAtIndex:indexPath.row] valueForKey:#"email"];
NSLog(#"VALOR DEL EMAIL=%#", email);
cell.detailTextLabel.text = email;
return cell;
}
What am I doing wrong?
You should call [self.tableView reloadData] from inside the completion block just after "SERVICIOS RECIBIDOS=%#" line.
Calling it outside the block as you did, will make the table reloads it contents before you receive it from the server.
Hope it helps you, amigo.
Related
How to get value from json?
this is first api
NSString *urlAsString = [NSString stringWithFormat:#"http://api.population.io/1.0/countries/?format=json"];
NSCharacterSet *set = [NSCharacterSet URLQueryAllowedCharacterSet];
NSString *encodedUrlAsString = [urlAsString stringByAddingPercentEncodingWithAllowedCharacters:set];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithURL:[NSURL URLWithString:encodedUrlAsString]
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(#"RESPONSE: %#",response);
NSLog(#"DATA: %#",data);
if (!error) {
// Success
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSError *jsonError;
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
if (jsonError) {
// Error Parsing JSON
} else {
// Success Parsing JSON
// Log NSDictionary response:
arr = [jsonResponse valueForKey:#"countries"];
NSLog(#"%#",arr);
[self.tableView reloadData];
}
} else {
//Web server is returning an error
}
} else {
// Fail
NSLog(#"error : %#", error.description);
}
}] resume];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return arr.count;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
cell.backgroundColor = [UIColor yellowColor];
cell.textLabel.text = [arr objectAtIndex:indexPath.row ];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;
{
NSString *str = [arr objectAtIndex:indexPath.row] ;
ViewController1 *vc=[self.storyboard instantiateViewControllerWithIdentifier:#"ViewController1"];
vc.str1 = [arr objectAtIndex:indexPath.row];
[self.navigationController pushViewController:vc animated:YES];
}
this is second one
NSString *urlAsString = [NSString stringWithFormat:#"http://api.population.io/1.0/wp-rank/1952-03-11/male/India/on/2001-05-11/?format=json"];
NSString *encodedString = [urlAsString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithURL:[NSURL URLWithString:encodedString]
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(#"RESPONSE: %#",response);
NSLog(#"DATA: %#",data);
if (!error) {
// Success
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSError *jsonError;
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
if (jsonError) {
// Error Parsing JSON
} else {
// Success Parsing JSON
// Log NSDictionary response:
// _str2 = [jsonResponse valueForKey:#"dob"];
/// NSLog(#"%#",_str2);
NSLog(#"%#",jsonResponse);
}
}
}
}
when i click particular country i should get data from that country
you need to use that str1 property that you are setting in didSelect method to make your URL, so replace the India with str1's value.
NSString *urlAsString = [NSString stringWithFormat:#"http://api.population.io/1.0/wp-rank/1952-03-11/male/%#/on/2001-05-11/?format=json", self.str1];
Note: You need to give proper name to your property, so better if you changed str1 to selectedCountry or something else.
I want to create a message conversation screen.I have two arrays, first is web_array and the second is local_array. First, I have one UITableViewCell in one UILabel, and one UITextField, and one UIButton. In the textfield, write any text and it will print on UITableViewCell label. TextField text is stored in a one array (local_array). (application run time local_array is empty).
And second array (web_array), web_array is stored in a web service get data, I want to web_array count on UITableViewCell label after local_array count in same label.
web_array data counting is over after just down local_array data counting start.
My english is very bad and i can't explain proper. seriously i'm so tired please help me and guide.
ViewController
#import "Chat_ViewController.h"
#import "chatview_Cell.h"
#interface Chat_ViewController () <UITableViewDataSource,UITableViewDelegate>
{
NSArray*web_array;
NSMutableArray*Local_array;
}
#end
#implementation Chat_ViewController
- (void)viewDidLoad {
[super viewDidLoad];
Local_array=[[NSMutableArray alloc]init];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"MYURL"]];
//create the Method "GET" or "POST"
[request setHTTPMethod:#"POST"];
//Pass The String to server(YOU SHOULD GIVE YOUR PARAMETERS INSTEAD OF MY PARAMETERS)
NSString *userUpdate =[NSString stringWithFormat:#"senderid=%#&recid=%#&",_chat_myuid.text,_chat_uid.text, nil];
//Check The Value what we passed
NSLog(#"the data Details is =%#", userUpdate);
//Convert the String to Data
NSData *data1 = [userUpdate dataUsingEncoding:NSUTF8StringEncoding];
//Apply the data to the body
[request setHTTPBody:data1];
//Create the response and Error
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&err];
NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];
//This is for Response
NSLog(#"got response==%#", resSrt);
NSArray *results = [json objectForKey:#"status"];
web_array = [results valueForKey:#"message"];
NSLog(#"your message %#",web_array);
//This is for Response
NSLog(#"got response==%#", resSrt);
if(resSrt)
{
NSLog(#"got response");
}
else
{
NSLog(#"faield to connect");
}
}
- (IBAction)send:(id)sender
{
NSString *textNameToAdd = self.mymsg.text; //mymsg is UITextField outlet
[Local_array addObject:textNameToAdd];
[self.table_view reloadData];
}
//TABLEVIEWCELL Code
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if ([Local_array count] > 0 && web_array.count>0)
{
return [Local_array count];
}
else
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
chatview_Cell *cell = [tableView dequeueReusableCellWithIdentifier:#"ht"];
if (cell==nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"Cell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
if (Local_array.count > 0 && web_array.count>0)
{
cell.other_msg.text=[NSString stringWithFormat:#"%#",[Local_array objectAtIndex:indexPath.row]];
}
cell.other_msg.text=[NSString stringWithFormat:#"%#",[web_array objectAtIndex:indexPath.row]];
return cell;
}
I am Developing An IOS App.On Button Click Show JSON Data In Tableview..But The Data Show ON Only First Cell Not On Other Cells..I Can Check The Data Through NSLog That Are Correct..But In Tableview Show In First Cells And Some Time App Crash And Error Data Parameters Are Nil..Warning Show on This Line
`"Incompatible Pointer Assigning To 'NSDictionary'
To
NSArray "[str = [BBServerJson sendPostRequest:json toUrl:url];]`
Any Help Or Advice Is Greatly Appreciated. Thanks In Advance.
//Button Click
BBAuthorViewController *BBAuthor =[[UIStoryboard storyboardWithName:#"Main" bundle:nil]instantiateViewControllerWithIdentifier:#"BBAuthor"];
BBAuthor.authorDetail=_adDetailsObj.authorDetail;
[self.navigationController pushViewController:BBAuthor animated:YES];
//Json
+(NSDictionary *)sendPostRequest:(NSDictionary *)params toUrl:(NSString *)urlString
{
NSMutableString *paramString =
[NSMutableString stringWithString:#""];
NSArray *keys = [params allKeys];
for (NSString *key in keys) {
[paramString appendFormat:#"%#=%#&",key,
[params valueForKey:key]];
}
NSString *postString = #"";
if ([paramString length] > 0)
postString = [paramString substringToIndex:
[paramString length]-1];
NSMutableURLRequest *request =[NSMutableURLRequest
requestWithURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[postString
dataUsingEncoding:NSUTF8StringEncoding]];
NSURLResponse *res;
NSError *error;
NSData *resp = [NSURLConnection sendSynchronousRequest:request
returningResponse:&res error:
&error];
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)res;
int statusCode;
statusCode = [httpResponse statusCode];
NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:resp options:NSJSONReadingMutableContainers error:&error];
return jsonArray;
}
NSString *url = #"https://boatbrat.com/wp-app-handler-boatsales.php";
NSMutableDictionary *json = [[NSMutableDictionary alloc]init];
[json setObject:#"AuthorListing" forKey:#"method"];
[json setObject:_authorDetail forKey:#"author"];
str = [BBServerJson sendPostRequest:json toUrl:url];
//Tableview
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return str.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
cell=[tableView dequeueReusableCellWithIdentifier:#"cell"];
NSArray *array = [str objectForKey:#"results"];
NSDictionary *dic= [array objectAtIndex:indexPath.row];
cell.textLabel.text = [dic objectForKey:#"author_name"];
return cell;
}
I think you are returning wrong row count in numberOfRowsInSection: method.
Change the return statement to,
return [[str objectForKey:#"results"] count];
I have a NSString as result of a URLRequest.
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if(responseString && responseString.length) {
// NSLog(#"DATOS RECIBIDOS EN HISTORIAL=%#", responseString);
NSError *jsonError;
NSData *objectData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
json = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&jsonError];
NSArray *messageArray = [json objectForKey:#"objects"];
// Parse and loop through the JSON
for (json in messageArray) {
NSString * code = [json objectForKey:#"code"];
NSDictionary *level2Dict = [json objectForKey:#"client"];
NSString *email = [level2Dict objectForKey:#"email"];
//NSString * nombre = someObject;
NSLog(#"CODIGO DE CLIENTE=%#",code);
NSLog(#"EMAIL DEL CLIENTE=%#",email);
}
Then I convert the string to a NSData that I deserialise into a json string.
Later I am able to iterate the array of dictionaries to get the value from some of the json objects.
But for hours I am trying to pass all this information to a table view, but I am not able. From the above code what should I do to get the needed information to be shown on a table view?
Thank you.
EDITED QUESTION:
#interface HistorialReservasViewController () {
NSArray *messageArray;
}
#end
- (void)viewDidLoad {
[super viewDidLoad];
UIBarButtonItem *newBackButton = [[UIBarButtonItem alloc] initWithTitle:#"Home" style:UIBarButtonItemStyleBordered target:self action:#selector(home:)];
self.navigationItem.leftBarButtonItem=newBackButton;
self.title = #"Corona";
//REQUEST DEL HISTORIAL
messageArray = [[NSArray alloc] init]; // just so array is not nil
//1. client , lo tomamos de la variable del sistema
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];//se crea una instancia de la variable del sistema
//LOS PARAMETROS NECESARIOS SON client y date
//buscamos client
NSString *idcliente = [defaults objectForKey:#"idUsuario"];
NSLog(#"ID CLIENTE=&%#",idcliente);
NSString *cliente = idcliente;
NSDateFormatter *formatter;
NSString *dateString;
formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd"];
dateString = [formatter stringFromDate:[NSDate date]];
NSLog(#"FECHA=%#", dateString);
NSString *fecha = dateString;
NSLog(#"CLIENTE=%#",cliente);
NSLog(#"FECHA=%#",fecha);
//request
NSURL *apiURL = [NSURL URLWithString:
[NSString stringWithFormat:#"http://hidden here/?client=%#&date=%#", cliente,fecha]];
NSURLRequest *request = [NSURLRequest requestWithURL:apiURL]; // this is using GET, for POST examples see the other answers here on this page
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if(data.length) {
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if(responseString && responseString.length) {
// NSLog(#"DATOS RECIBIDOS EN HISTORIAL=%#", responseString);
NSError *jsonError;
NSData *objectData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
json = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&jsonError];
messageArray = [json objectForKey:#"objects"];
// Parse and loop through the JSON
for (json in messageArray) {
NSString * code = [json objectForKey:#"code"];
NSDictionary *level2Dict = [json objectForKey:#"client"];
NSString *email = [level2Dict objectForKey:#"email"];
// id someObject = [level2Dict objectForKey:#"name"];
// NSLog(#"NOMBRE===%#",someObject);
//NSString * nombre = someObject;
NSLog(#"CODIGO DE CLIENTE=%#",code);
NSLog(#"EMAIL DEL CLIENTE=%#",email);
}
}
}
}];
NSLog(#"NUMERO ED ITEMS=%lu", (unsigned long)messageArray.count);
}
//METODOS PARA LA CONEXION
-(void)home:(UIBarButtonItem *)sender {
[self performSegueWithIdentifier:#"mapa_segue" sender:self];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [messageArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
cell.textLabel.text = [[messageArray objectAtIndex:indexPath.row] objectForKey:#"code"];
return cell;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
return NO;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
}
You are not passing your data to your tableview at all. You need to create global array and initializes this array in viewDidLoad, populate it like you do and use it in your tableview functions.
NSArray *messageArray;
in view did load change this line
-(void)viewDidLoad{
messageArray = [[NSArray alloc] init]; // just so array is not nil
messageArray = [json objectForKey:#"objects"];
}
And use this array to populate your tableview
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [messageArray count]; //this will ensure you will have as many cells in your table view as there are values in your array
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
//here you use your array and fill cell with your data
// you need to have a UILabel in cell which is called "codeLabel" but feel free to name it whatever you want
cell.codeLabel.text = [[messageArray objectAtIndex:indexPath.row] objectForKey:#"code"]; //to fill your codelabel with code value from array
cell.otherLabel.text = [[messageArray objectAtIndex:indexPath.row] objectForKey:#"other"]; //just another value
return cell;
}
EDIT
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if(data.length) {
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if(responseString && responseString.length) {
// NSLog(#"DATOS RECIBIDOS EN HISTORIAL=%#", responseString);
NSError *jsonError;
NSData *objectData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
json = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&jsonError];
messageArray = [json objectForKey:#"objects"];
NSLog(#"NUMERO ED ITEMS=%lu", (unsigned long)messageArray.count);
//all UI updates must be called from main thread, thats why reload data must be wrapped in this call for more info google "ios GCD"
dispatch_async(dispatch_get_main_queue){
[tableView reloadData];
}
// Parse and loop through the JSON
for (json in messageArray) {
NSString * code = [json objectForKey:#"code"];
NSDictionary *level2Dict = [json objectForKey:#"client"];
NSString *email = [level2Dict objectForKey:#"email"];
// id someObject = [level2Dict objectForKey:#"name"];
// NSLog(#"NOMBRE===%#",someObject);
//NSString * nombre = someObject;
NSLog(#"CODIGO DE CLIENTE=%#",code);
NSLog(#"EMAIL DEL CLIENTE=%#",email);
}
}
}
}];
In my iOS app I've to parse a JSON file. From this JSON I need the following stuff: name, image width and image height. To get image name I'ven't any problem, to get image with and height I use the following code:
- (void) loadImageFromWeb:(NSString *)urlImg forName:(NSString*)name {
NSURL* url = [NSURL URLWithString:urlImg];
//NSURLRequest* request = [NSURLRequest requestWithURL:url];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSString *authCredentials =#"reply:reply";
NSString *authValue = [NSString stringWithFormat:#"Basic %#",[authCredentials base64EncodedStringWithWrapWidth:0]];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse * response,
NSData * data,
NSError * error) {
if (!error){
UIImage* image = [[UIImage alloc] initWithData:data];
imageWidth = image.size.width;
imageHeight = image.size.height;
imgWidth = [NSString stringWithFormat:#"%f", imageWidth];
imgHeight = [NSString stringWithFormat:#"%f", imageHeight];
self.dictWithDataForPSCollectionView = #{#"title": name,
#"width": imgWidth,
#"height": imgHeight};
[self.arrayWithData addObject:self.dictWithDataForPSCollectionView];
NSLog(#"DATA ARRAY: %#", self.arrayWithData);
} else {
NSLog(#"ERRORE: %#", error);
}
}];
}
You can see that I save the name, image width and image height in a NSDictionary then I put this in an NSMutableArray. When it execute the NSLog, I see this:
DATA ARRAY: (
{
height = "512.000000";
title = "Eau de Toilet";
width = "320.000000";
},
{
height = "1049.000000";
title = "Eau de Toilet";
width = "1405.000000";
}
)
My question is how to get this information back in the class who call my json parser, I tried to access to the variable in this way:
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
recivedData = [[NSMutableData alloc]init];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[recivedData appendData:data];
NSString *string = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"JSON: %#", string);
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary *json;
NSError *err;
json = [NSJSONSerialization JSONObjectWithData:recivedData options:NSJSONReadingMutableLeaves error:&err];
JsonCategoryReader *reader = [[JsonCategoryReader alloc]init];
[reader parseJson:json];
}
But when I run the code it shows me an empty array. How I can have the information in this class?
UPDATE:
The JSON I've to parse is the following:
{
"1":{
"entity_id":"1",
"type_id":"simple",
"sku":"EAU_DE_TOILET_1",
"description":"A passionate scent with the zest of exclusive Zegna Bergamot, sparked by Violettyne Captive, and the warmth of Vetiver and Cedarwood",
"short_description":"EAU DE TOILETTE NATURAL SPRAY",
"meta_keyword":null,
"name":"Eau de Toilet",
"meta_title":null,
"meta_description":null,
"regular_price_with_tax":60,
"regular_price_without_tax":60,
"final_price_with_tax":60,
"final_price_without_tax":60,
"is_saleable":true,
"image_url":"http:\/\/54.204.6.246\/magento8\/media\/catalog\/product\/cache\/0\/image\/9df78eab33525d08d6e5fb8d27136e95\/p\/r\/product_100ml.png"
},
"2":{
"entity_id":"2",
"type_id":"simple",
"sku":"EAU_DE_TOILET_2",
"description":"A passionate scent with the zest of exclusive Zegna Bergamot, sparked by Violettyne Captive, and the warmth of Vetiver and Cedarwood",
"short_description":"EAU DE TOILETTE NATURAL SPRAY",
"meta_keyword":null,
"name":"Eau de Toilet",
"meta_title":null,
"meta_description":null,
"regular_price_with_tax":60,
"regular_price_without_tax":60,
"final_price_with_tax":60,
"final_price_without_tax":60,
"is_saleable":true,
"image_url":"http:\/\/54.204.6.246\/magento8\/media\/catalog\/product\/cache\/0\/image\/9df78eab33525d08d6e5fb8d27136e95\/s\/c\/scheda_non_shop.jpg"
}
}
My method parseJson do the following:
- (void)parseJson:(NSDictionary *)jsonDict {
// Controllo che il json sia stato ricevuto
if (jsonDict) {
self.nameArray = [[NSMutableArray alloc]init];
self.imgUrlArray = [[NSMutableArray alloc]init];
self.dictWithDataForPSCollectionView = [[NSDictionary alloc]init];
self.arrayWithData = [[NSMutableArray alloc]init];
[self createArrayWithJson:jsonDict andIndex:1];
[self createArrayWithJson:jsonDict andIndex:2];
}
- (void)createArrayWithJson:(NSDictionary*)json andIndex:(NSString*)i {
NSDictionary *products = [json objectForKey:i];
NSString *name = [products objectForKey:#"name"];
NSString *imgUrl = [products objectForKey:#"image_url"];
// Scarico l'immagine e calcolo le dimensioni
if (name != nil && imgUrl != nil) {
[self loadImageFromWeb:imgUrl forName:name];
}
}
I hope you understand what I did
what happen is that your class is make before that your json is download, for have a good sequence you have to call your method for parse the json inside the completionHandler block, when you are sure that it is download. then when you have your object load you can parse it like this example:
for (NSDictionary *dic in reader.arrayWithData){
NSLog("height: %#",[dic objectForKey:#"height"]);
NSLog("title: %#",[dic objectForKey:#"title"]);
NSLog("width: %#",[dic objectForKey:#"width"]);
}