Parsing data from googleapi - ios

I'm trying to build an app that uses data from this url: http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=8&q=http%3A%2F%2Fnews.google.com%2Fnews%3Foutput%3Drss
So far, I'm downloading it with this:
- (void) downloadData {
NSString *url = #"http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=8&q=http%3A%2F%2Fnews.google.com%2Fnews%3Foutput%3Drss";
// Create NSUrlSession
NSURLSession *session = [NSURLSession sharedSession];
// Create data download taks
[[session dataTaskWithURL:[NSURL URLWithString:url]
completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {
NSError *jsonError;
self.issueData = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:&jsonError];
// Log the data for debugging
NSLog(#"DownloadedData:%#",self.issueData);
// Use dispatch_async to update the table on the main thread
// Remember that NSURLSession is downloading in the background
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
}] resume];
}
and trying to insert it into my table view cells with this:
- (CustomTableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
CustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"customTableViewCell" forIndexPath:indexPath];
NSLog(#"Working on cell:%ld",(long)indexPath.row);
NSDictionary *thread = [self.issueData objectAtIndex:indexPath.row];
cell.title.text = [thread objectForKey:#"description"];
cell.date.text = [thread objectForKey:#"publishedDate"];
cell.content.text = [thread objectForKey:#"contentSnippet"];
return cell;
Anyone know what I'm doing wrong?

Your top level object for json is not array so
NSDictionary *thread = [self.issueData objectAtIndex:indexPath.row]; this will not work. You top level object is dictionary so parsing will be as
(CustomTableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
CustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"customTableViewCell" forIndexPath:indexPath];
NSLog(#"Working on cell:%ld",(long)indexPath.row);
NSDictionary *thread = [self.issueData objectForKey:#"responseData"];
NSDictionary *feed = [thread objectForKey:#"feed"];
cell.title.text = [feed objectForKey:#"description"];
NSArray *entries = [feed objectForKey:#"entries"];
NSDictionary *posts = entries[indexPath.row];
cell.date.text = [posts objectForKey:#"publishedDate"];
cell.content.text = [posts objectForKey:#"contentSnippet"];
return cell;
}

I guess right way for parsing it as follow's
- (void) downloadData {
NSString *url = #"http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=8&q=http%3A%2F%2Fnews.google.com%2Fnews%3Foutput%3Drss";
// Create NSUrlSession
NSURLSession *session = [NSURLSession sharedSession];
// Create data download taks
[[session dataTaskWithURL:[NSURL URLWithString:url]
completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {
NSError *jsonError;
NSDictionary * dict;
dict= [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:&jsonError];
dispatch_async(dispatch_get_main_queue(), ^{
if ([dict valueForKey:#"responseData"]) {
if([[dict valueForKey:#"responseData"] isKindOfClass:[NSDictionary class]]){
if ([(NSDictionary *)[dict valueForKey:#"responseData"] valueForKey:#"feed"]) {
if ([[(NSDictionary *)[dict valueForKey:#"responseData"] valueForKey:#"feed"]isKindOfClass:[NSDictionary class]]) {
NSDictionary * feedDict = [(NSDictionary *)[dict valueForKey:#"responseData"] valueForKey:#"feed"];
if ([feedDict valueForKey:#"description"]){
NSLog(#"%#",[feedDict valueForKey:#"description"]);
}
if ([[feedDict valueForKey:#"entries"] isKindOfClass:[NSArray class]]){
for (NSDictionary * dic in (NSArray *)[feedDict valueForKey:#"entries"]) {
NSLog(#"published = %#",[dic valueForKey:#"publishedDate"]);
}
}
if ([[feedDict valueForKey:#"entries"] isKindOfClass:[NSArray class]] ){
for (NSDictionary * dic in (NSArray *)[feedDict valueForKey:#"entries"]) {
NSLog(#"contentSnippet = %#",[dic valueForKey:#"contentSnippet"]);
}
}
}
}
}
}
});
}] resume];}
I just logged the required keys to console you can add them to arrays and use them anywhere you want.

Related

how do get values when i click on particular country dynamically like this is showing of india

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.

model class data Retriving

I have implemented a UITableview in ViewController1 and retrieving the data from JSON. I Want to display the cell with the Image,Tittle and Sub tittle.I am using a TableClass as model class for that
dispatch_async(dispatch_get_main_queue(), ^{
NSURLSession*session=[NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:#"https://itunes.apple.com/search?term=music"] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"%#", json);
NSArray*entryarr=[json objectForKey:#"results"];
TableClass*tc=[[TableClass alloc]init];
for (NSDictionary*appDict in entryarr) {
NSString*str=[appDict objectForKey:#"artistName"];
[tc setTittle:str];
NSLog(#"artist Name=%#",tc.tittle);
//setting Subtittle
NSString*sub=[appDict objectForKey:#"country"];
[tc setSubtittle:sub];
NSLog(#"artist Name=%#",tc.subtittle);
NSString*imageStr=[appDict objectForKey:#"artworkUrl60"];
[tc setImage:imageStr];
NSURL*imageURL=[NSURL URLWithString:imageStr];
NSData*imageData=[[NSData alloc]initWithContentsOfURL:imageURL];
[self.imageArray addObject:imageData];
[_tableArray addObject:tc];
NSLog(#"%# name of tittle",[_tableArray objectAtIndex:0]);
}
NSLog(#"%lu %lu %lu",(unsigned long)self.tableArray.count,(unsigned long)self.tableArray.count,(unsigned long)self.tableArray.count);
[self.tableView reloadData];
}];
[dataTask resume];
});
}
But Now i display the data By
cell.textLabel.text=[[self.tableArray objectAtIndex:indexPath.row]valueForKey:#"_tittle"];
cell.detailTextLabel.text=[[self.tableArray objectAtIndex:indexPath.row]valueForKey:#"_subtittle"];
cell.imageView.image=[UIImage imageWithData:[[self.tableArray objectAtIndex:indexPath.row]valueForKey:#"_image"]];
But I feel that method is not optimise, So I want to display Data through Model class itself How can i do it...?
TableClass.h
#import <Foundation/Foundation.h>
#interface TableClass : NSObject
#property(nonatomic,strong) NSString *title;
#property(nonatomic,strong) NSString *subtittle;
#property(nonatomic,strong) NSString *imageURL;
#property(nonatomic,strong) NSData *imageData;
#end
in your ViewController.m
-(void)getData
{
NSURLSession*session=[NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:#"https://itunes.apple.com/search?term=music"] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"%#", json);
NSArray*entryarr=[json objectForKey:#"results"];
self.tableArray=[[NSMutableArray alloc]init];
for (NSDictionary*appDict in entryarr)
{
TableClass *classModel=[[TableClass alloc]init];
classModel.title=[appDict objectForKey:#"artistName"];
classModel.subtittle=[appDict objectForKey:#"country"];
classModel.imageURL=[appDict objectForKey:#"artworkUrl60"];
classModel.imageData=[NSData dataWithContentsOfURL:[NSURL URLWithString:classModel.imageURL]];
[self.tableArray addObject:classModel];
}
NSLog(#"%lu %lu %lu",(unsigned long)self.tableArray.count,(unsigned long)self.tableArray.count,(unsigned long)self.tableArray.count);
dispatch_async(dispatch_get_main_queue(), ^{
//update UI in main thread.
[self.myTableView reloadData];
});
}];
[dataTask resume];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return self.tableArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier= #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:
UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
TableClass *tableclassModel=[self.tableArray objectAtIndex:indexPath.row];
cell.textLabel.text=tableclassModel.title;
cell.detailTextLabel.text=tableclassModel.subtittle;
[cell.imageView setImage:[UIImage imageWithData:tableclassModel.imageData]];
return cell;
}
In this example you don't need an extra array to store images.
Let me know if you have any query.

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

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.

Data from API call and jsonobject is not carrying over when called

I'm calling this API and it's jsonobject in a segue, and trying to push it into a view controller, but it's not carrying the data. In my Below code it prints just fine in the call, but the other two prints come up with null.
Is there something I'm missing to make the data persistent?
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"showChangeDetail"]) {
NSIndexPath *indexPath = nil;
BNRItem *item = nil;
//BDItemChangeDetailAPI *itemAPI = nil;
NSArray *items = [[BNRItemStore sharedStore] allItems];
if (self.searchDisplayController.active) {
indexPath = [self.searchDisplayController.searchResultsTableView indexPathForSelectedRow];
item = [searchResults objectAtIndex:indexPath.row];
} else {
indexPath = [self.tableView indexPathForSelectedRow];
//item = items[indexPath.row];
item = [items objectAtIndex:indexPath.row];
}
NSLog(#"111111%#", self.APIItem);
[self fetchFeedAPIChangeDetail];
NSLog(#"222222%#", self.APIItem);
BDChangeApproveController *destViewController = segue.destinationViewController;
destViewController.itemAPI = self.APIItem;
}
}
- (void)fetchFeedAPIChangeDetail
{
//NSString *changeorder = changeOrder;
// NSString *requestString = [#"http://URL.com];
NSString *requestString = #"http://URL.com";
NSURL *url = [NSURL URLWithString:requestString];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
NSURLSessionDataTask *dataTask =
[self.session dataTaskWithRequest:req
completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error){
NSDictionary *jsonObject1 = [NSJSONSerialization JSONObjectWithData:data
options:0
error:nil];
//NSLog(#"%#", jsonObject1);
self.APIItem = jsonObject1[#"CoDetail"];
NSLog(#"%#", self.APIItem);
}];
[dataTask resume];
}
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// show loading indicator
__weak typeof(self) weakSelf = self;
[[BNRItemStore sharedStore] fetchFeedAPIChangeDetail:^(NSArray *array, NSError *err)
{
[weakSelf performSegueWithIdentifier:#"showChangeDetail" sender:weakSelf];
// hide loading indicator
}];
}

Resources