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);
}
}
}
}];
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 new to iOS. I have one UIViewController in that added one tableview and segmented control. If I press the segmented value = 0, I want to the first custom cell with loading images and title and segment value = 1, I want to display my second custom cell with UICollectionView with loading of images and title, how can I do that please help me? Here is some of my code:
MenuViewController.m
-(void)callSegmentSelected
{
value=(int)segment.selectedSegmentIndex;
if (segment.selectedSegmentIndex == 0)
{
NSString *urlString = [NSString stringWithFormat:#"http://API"];
NSString *jsonString = #"";
NSData *myJSONData =[jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSMutableData *body = [NSMutableData data];
[body appendData:[NSData dataWithData:myJSONData]];
[request setHTTPBody:body];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
if(str.length > 0)
{
NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSLog(#"%#", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]);
listBannerArray =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
[progressHud hide:YES];
[self.tableViewContest reloadData];
}
else
{
NSLog(#"Error");
}
}
Here is my CellForRowAtIndexPath
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellId = #"Cell";
MenuTableViewCell *cell = (MenuTableViewCell *)[tableViewContest dequeueReusableCellWithIdentifier:cellId];
if (cell == nil)
{
NSArray * myNib;
myNib =[[NSBundle mainBundle]loadNibNamed:#"MenuTableViewCell" owner:self options:nil];
cell = (MenuTableViewCell *)[myNib lastObject];
}
if(value == 0)
{
#try
{
if((NSNull *)[[listBannerArray objectAtIndex:indexPath.row] objectForKey:#"listbanner"] != [NSNull null])
{
if([[[listBannerArray objectAtIndex:indexPath.row] objectForKey:#"listbanner"] length] > 0)
{
NSURL *imageURL = [NSURL URLWithString:[[listBannerArray objectAtIndex:indexPath.row] objectForKey:#"listbanner"]];
[cell.listBanner sd_setImageWithURL:imageURL
placeholderImage:[UIImage imageNamed:#"profilepic_bg"]];
}
else
{
}
}
}
#catch (NSException *exception)
{
}
if((NSNull *)[[listBannerArray objectAtIndex:indexPath.row] objectForKey:#"examtitle"] != [NSNull null])
{
if([[[listBannerArray objectAtIndex:indexPath.row] objectForKey:#"examtitle"] length] > 0)
{
cell.examTitle.text = [[listBannerArray objectAtIndex:indexPath.row] objectForKey:#"examtitle"];
}
else
{
cell.examTitle.text = #"Data Error";
}
}
else
{
cell.examTitle.text = #"Data Error";
}
}
When Click on SegmentIndex=0 Screen like this
When Click on SegmentIndex=1 like this
You can create the enum for differentiate the segment action.
Step 1 : Create the enum for the selection.
typedef enum {
OPTION_FIRST = 0,
OPTION_SECOND
} SEGMENT_SELECTION;
Step 2 : On your MenuViewController.m
1) Create the instance of SEGMENT_SELECTION
#property(nonatomic) SEGMENT_SELECTION segmentSelection;
2) Assign the value to segmentSelection
-(void)callSegmentSelected
{
if (segment.selectedSegmentIndex == 0)
segmentSelection = OPTION_FIRST
else
segmentSelection = OPTION_SECOND
[self.tableViewContest reloadData];//For update the content in tableview
}
Step 3 : Write the below code on CellForRowAtIndexPath
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(segmentSelection == OPTION_FIRST) {
//Load the content of FIRST segment action
}
else {
//Load the content of SECOND segment action
}
}
Hope it works for you.
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 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.