JSON data show on first cell - ios

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];

Related

How to count two arrays in a single label in UITableViewCell? Objective-C

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;
}

How to maintain two custom cells in one tableview with segment selection?

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.

Populating a table view form JSON

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);
}
}
}
}];

How to populate UITableView with JSON data?

I'm struggling to figure out what i am doing wrong. I am basically trying to populate the my UITableView with json data. In the console I can see the results but just don't know why the data is not displayed in the tableview. I have looked at similar questions and answers but none is a solution to my problem.
Advice or help please;
#pragma mark - Private method implementation
-(void)loadData{
// Form the query.
#try {
NSString *get =[[NSString alloc] initWithFormat:#""];
NSString *getRegions = [NSString stringWithFormat:#"JSON URL HERE",self.sessionId, self.companyId];
NSURL *url=[NSURL URLWithString:getRegions];
NSLog(#"Get regions: %#", url);
NSData *postData = [get dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"GET"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPBody:postData];
//[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"Reponse code: %ld", (long)[response statusCode]);
if ([response statusCode] >= 200 && [response statusCode] < 300)
{
NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"Response ==> %#", responseData);
#try{
NSError *error = nil;
regionsJson = [[NSMutableArray alloc]init];
//[jsonData removeAllObjects];
regionsJson = [NSJSONSerialization JSONObjectWithData:urlData options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:&error];
NSArray *tblArray = [NSArray arrayWithObject:regionsJson];
}
#catch (NSException *e){
NSLog(#"Try catch block: %#", e);
}
#finally{
// [self.tblRegion reloadData];
NSLog(#"finally");
}
structureJson =[regionsJson valueForKey:#"structure"];
companyJson =[structureJson valueForKey:#"company"];
_barBtnCompanyName.title = [companyJson valueForKey:#"company_name"];
NSLog(#"Get company name: %#", [companyJson valueForKey:#"company_name"]);
for (int i =0 ; i < regionsJson.count; i++){
regionsJson = [companyJson objectForKey:#"regions"];
NSString *regionName = [NSString stringWithFormat:#"%#", [regionsJson valueForKey:#"region_name"]];
NSLog(#"Region name: %#",regionName);
// [regionsJson addObject:regionName];
NSString *alarmCount = [NSString stringWithFormat:#"%#", [regionsJson valueForKey:#"alarm_cnt"]];
NSLog(#"Alarm count: %#", alarmCount);
// [regionsJson addObject:alarmCount];
}
}
}
#catch (NSException * e) {
NSLog(#"Exception: %#", e);
}
// Reload the table view.
[self.tblRegion reloadData];
}
#pragma mark - UITableView method implementation
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
NSLog(#"Number of rows: %lu", (unsigned long)regionsJson.count);
return [regionsJson count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"CellRegions";
// Dequeue the cell.
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
// Set the loaded data to the appropriate cell labels.
cell.textLabel.text = [[regionsJson objectAtIndex:indexPath.row] objectForKey:#"region_name"];
cell.detailTextLabel.text = [[regionsJson objectAtIndex:indexPath.row] objectForKey:#"alarm_cnt"];
[cell setAccessoryType: UITableViewCellAccessoryDisclosureIndicator];
NSLog(#"Table cell: %#", cell);
return cell;
}
My code is just fine, i did a stupid omission of this declaration.
-(void)viewDidLoad{
[super viewDidLoad];
// Do any additional setup after loading the view.
self.tblRegion.delegate = self;
self.tblRegion.dataSource = self;
[self loadData];
}

Table view populated from NSMutableArray not showing anything

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.

Resources